数据绑定依赖项属性到数据对象 [英] Data binding dependency property to data object
问题描述
我有一个带有DependencyProperty的DependencyObject:
I have a DependencyObject with a DependencyProperty:
public class DependencyObjectClass: DependencyObject
{
public static DependencyProperty BooleanValueProperty = DependencyProperty.Register("BooleanValue", typeof (bool), typeof (DependencyObjectClass));
public bool BooleanValue
{
get { return (bool)GetValue(BooleanValueProperty); }
set { SetValue(BooleanValueProperty, value); }
}
}
我也有数据源类:
public class DataSource: INotifyPropertyChanged
{
private bool _istrue;
public bool IsTrue
{
get { return _istrue; }
set
{
_istrue = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("IsTrue"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
我正在尝试使用以下代码绑定上述两个对象:
I am trying to bind the two above objects with this code:
var dependencyObject = new DependencyObjectClass();
var dataSource = new DataSource();
var binding = new Binding("IsTrue");
binding.Source = dataSource;
binding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(dependencyObject, DependencyObjectClass.BooleanValueProperty, binding);
每当我更改DependencyObjectClass的BooleanValue属性时,DataSource都会做出反应,但不会起作用其他方法(更改DataSource的IsTrue属性对DependencyObjectClass无效)。
Whenever I change the BooleanValue property on DependencyObjectClass, the DataSource does react, but it doesn't work the other way around (changing IsTrue property on DataSource does nothing for DependencyObjectClass).
我在做什么错?我是否必须手动处理OnPropertyChanged事件?如果是的话,那将有些令人失望,因为我期望它会自动完成。
What am I doing wrong? Do I have to manually handle the OnPropertyChanged event? If yes then that would be a bit disappointing, as I was expecting this to be done automatically.
推荐答案
更改DataSource上的IsTrue属性对于
DependencyObjectClass
changing IsTrue property on DataSource does nothing for DependencyObjectClass
我想您是根据<$永远不会调用c $ c> DependencyObjectClass.BooleanValue 属性设置器。实际上,WPF不会这样做。而是直接设置依赖项属性的值,就像直接调用 SetValue
。
I guess you conclude this from the fact that the DependencyObjectClass.BooleanValue
property setter is never called. In fact WPF does not do that. Instead it directly sets the value of the dependency property, just like calling SetValue
directly.
请参见定义依赖项属性的清单和自定义依赖项属性的含义以得到解释。
为了获取有关已更改的依赖项属性值的通知,您必须注册 PropertyChangedCallback ,其依赖属性属性元数据位于 DependencyProperty.Register 。
In order to get notified about a changed dependency property value, you would have to register a PropertyChangedCallback with the dependency property metadata in DependencyProperty.Register.
这篇关于数据绑定依赖项属性到数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!