2011-03-17 76 views
4

我有,现在我的WPF应用程序还挺可怕的问题...自定义用户控件“的IsEnabled”数据绑定不工作

我已经使用编辑器部件的细节自定义用户控件。它应该从未启用开始,并在用户选择要编辑的组件时立即启用。

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

这里是我的代码:

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

EditorEnabled是在我的视图模型(VmComponent)的属性,并且默认为false,当用户选择了一个组件或创建一个

只是为了成为真正的记录,在我的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工作大约一个星期前,因此我可能错过了一些重要的...

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

+0

断点停在'_editorEnabled = value;'? – 2011-03-17 12:05:08

+0

正确创建了VmComponent?据我所知,该绑定不会初始化一个新的对象。 – Harry 2011-03-17 12:18:56

+0

@Fun Mun Pieng:是的,它通过了setter @Harry:是的,VmComponent被创建,并且适合所有其他需求,只有这个不工作 – Damascus 2011-03-17 12:53:02

回答

2

您应该添加的DependencyProperty的结合才能正常工作。 See here for more information.

代码隐藏:

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); } 
} 
+0

真的值得添加吗?我的意思是,该控件自然具有IsEnabled属性。我认为添加一个与IsEnabled具有相同角色的DependencyProperty会导致错误编码: -/ – Damascus 2011-03-17 12:46:23

+0

是 - 依赖属性在XAML中大量使用 - 请参阅我发布的链接以获取更多信息。我用一个例子更新了我的答案。 – 2011-03-17 12:52:43

+0

不,不需要添加DependencyProperty - 代码看起来应该像现在这样工作。我会尝试显式设置datacontext - 或者对VmComponent属性进行属性更改 - 或者在InitializeComponent之前设置属性值。 – 2011-03-17 12:58:44

1

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

为了解决这个问题,我给IsEnabled的绑定指定了一个合适的源。一旦我做到了,控制开始按预期工作。

希望有所帮助。

0

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

然后,您可以简单地使用dockpanel而不是自定义控件进行绑定。