奇怪的行为绑定DataContext& UserControl上的IsEnabled-Property

时间:2012-04-16 08:58:06

标签: c# wpf binding user-controls

我有一种奇怪的约束行为DataContext& IsEnabled UserControl的属性。

在我的页面中,我使用像这样的UserControl:

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

还有一个像这样的按钮:

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

说明:

转换器将currentServiceState-Enum转换为bool。我的按钮的行为符合我的预期(En / DisAbled)。

问题:我的按钮被正确启用/禁用,但我的usercontrol中的控件不是。

DataContext(HTTPS)实际上不是null:

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

我试图在我的UserControls绑定上使用FallbackValue = False,但是UserControl甚至被禁用...

有人可以解释这些行为吗? 非常感谢。

更新

我的解决方法:

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

1 个答案:

答案 0 :(得分:0)

您不应该绑定自己的DataContext。任何绑定操作都使用DataContext,因此绑定DataContext是一个循环操作。即使这样有效,也无法保证绑定的创建顺序,因此在IsEnabled绑定到新值之前,DataContext属性可能会被绑定。

相反,您应该具体说明属性的完整路径。例如:

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