简体   繁体   中英

Strange Behavior Binding DataContext & IsEnabled-Property on UserControl

i have a strange behavior of binding DataContext & IsEnabled Property of a UserControl.

In my page, I use a UserControl like this:

<httpsPort:HttpsPort DataContext="{Binding Path=Https}"
    IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}" />

And a Button such as this:

<Button Content="start service"
    IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}"
    Command="{Binding CmdConfigureService}" [...] />

explanation:

the converter converts the currentServiceState-Enum to bool. My Button behaves as I expect it (En/DisAbled).

problem: my button is correctly en/disabled, but the controls in my usercontrol are not.

The DataContext (HTTPS) is actually not null:

private HttpsPortViewModel _https;
    public HttpsPortViewModel Https
    {
        get
        {
            if (_https == null)
            {
                _https = new HttpsPortViewModel();
            }
            return _https;
        }
        set
        {
            _https = value;
            NotifyPropertyChanged(() => Https);
        }
    }

i have tried to use FallbackValue=False on my UserControls Binding, but then UserControl is even Disabled...

Can anybody explain these behavior? Thanks a lot.

Update:

My Workaround:

<Grid IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}">
    <httpsPort:HttpsPort DataContext="{Binding Path=Https}" />
</Grid>

You should not be binding your own DataContext . Any binding operation USES the DataContext , so binding your DataContext is a circular operation. Even if this worked there is no guarantee in what order your bindings are created, so your IsEnabled property could be bound before your DataContext was bound to its new value.

Instead you should specificy the full path for properties. eg:

<httpsPort:HttpsPort IsEnabled="{Binding Https.CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM