5

我的 WPF 应用程序现在有一个可怕的问题......

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

问题是: IsEnabled 属性甚至没有改变。

这是我的代码:

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
                        IsEnabled="{Binding EditorEnabled}"
                              DataContext="{Binding VmComponent}" />

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

仅作记录,在我的 ViewModel 中:

private Boolean _editorEnabled = false;

    public Boolean EditorEnabled
    {
        get { return _editorEnabled; }
        set 
        {
            _editorEnabled = value;
            OnPropertyChanged("EditorEnabled");
        }
    }

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

我还做了一件非常愚蠢的事情来试图弄清楚发生了什么:我创建了一个转换器(非常有用 - 将布尔值转换为布尔值 - 嗯),在它上面设置了一个断点,然后......代码永远不会到达。

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
                        IsEnabled="{Binding EditorEnabled, Converter={StaticResource BoolConverter}}"
                              DataContext="{Binding VmComponent}" />

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

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

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

4

3 回答 3

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); }
}
于 2011-03-17T12:07:26.213 回答
1

我认为的问题是用户控件的 DataContext 属性上有一个绑定。这意味着 EditorEnabled 属性应该是 VmComponent 对象中的一个属性。至少那是我的问题所在。

为了解决这个问题,我为 IsEnabled 的绑定指定了一个适当的来源。一旦我这样做了,控件就开始按预期工作。

希望有帮助。

于 2012-08-25T12:14:24.083 回答
0

将您的控件封装在 DockPanel 中(例如)将不再需要 DependencyProperty。

然后,您可以简单地使用停靠面板而不是自定义控件进行绑定。在 Dockpanel 上设置绑定到 IsEnabled 的变量将自动启用或禁用 Dockpanel 中包含的项目。

于 2014-02-25T08:03:45.883 回答