自定义UserControl“ IsEnabled”数据绑定不起作用

Dam*_*cus 5 c# wpf binding mvvm isenabled

我的WPF应用程序现在有点问题...

我有一个用于编辑组件详细信息的自定义UserControl。它应该从未启用开始,并在用户选择要编辑的组件后立即启用。

问题是:IsEnabled属性甚至都不会更改。

这是我的代码:

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
                        IsEnabled="{Binding EditorEnabled}"
                              DataContext="{Binding VmComponent}" />
Run Code Online (Sandbox Code Playgroud)

EditorEnabled是我的ViewModel(VmComponent)中的一个属性,默认为false,当用户选择一个组件或创建一个组件时变为true

仅作记录,在我的ViewModel中:

private Boolean _editorEnabled = false;

    public Boolean EditorEnabled
    {
        get { return _editorEnabled; }
        set 
        {
            _editorEnabled = value;
            OnPropertyChanged("EditorEnabled");
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试启动我的应用程序时,UserControl正在启动...启用。我到处都添加了断点,EditorEnabled从一开始就是假的。

我也做了一件非常愚蠢的事情,试图弄清楚发生了什么:我创建了一个转换器(非常有用-将布尔值转换为布尔值-嗯),在其上设置一个断点,然后……代码从未到达。

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
                        IsEnabled="{Binding EditorEnabled, Converter={StaticResource BoolConverter}}"
                              DataContext="{Binding VmComponent}" />
Run Code Online (Sandbox Code Playgroud)

这可能意味着永远不会设置属性isEnabled,因为永远不会到达转换器。

您在那看到任何问题吗?大约一周前,我开始在WPF工作,因此我可能错过了一些重要的东西...

非常感谢您的宝贵时间 :-)

Jos*_* M. 3

您应该添加 DependencyProperty 以使绑定正常工作。浏览此处获取更多信息。

隐藏代码:

public static readonly DependencyProperty EditorEnabledDependencyProperty = DependencyProperty.Register("EditorEnabled", typeof(bool), typeof(UcComponentEditor), new PropertyMetadata(false));

public bool EditorEnabled
{
    get { return (bool)base.GetValue(UcComponentEditor.EditorEnabledDependencyProperty); }
    set { base.SetValue(UcComponentEditor.EditorEnabledDependencyProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)