【发布时间】:2013-02-10 19:43:06
【问题描述】:
我有一个带有 DependencyProperty 的 DependencyObject:
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;
}
我正在尝试用这段代码绑定以上两个对象:
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 没有任何作用)。
我做错了什么?我是否必须手动处理 OnPropertyChanged 事件?如果是,那将有点令人失望,因为我希望这会自动完成。
【问题讨论】:
-
顺便问一句,这样做的目的是什么?您正在创建自定义控件吗?
-
我也看到了绑定布尔属性的一些问题。如果我们将相同的值从 VM 通知到 View,它不会反映在 DependencyProperty 的设置器中。就像你有 IsTrue 的真值然后你再次分配 true对它来说,DependencyProperty 的设置器不会反映它。这意味着如果你再次设置相同的值,它不会反映到 DependencyProperty 的设置器。
-
HighCore,我基本上是在非 WPF 对象上实现 MVVM 模式。我正在编写一个加载项,我需要在其中使用一些第三方 UI 元素,因此我选择将它们包装在我自己的类中,这些类派生自 DependencyObject。欢迎提出任何建议。
标签: c# .net wpf data-binding dependency-properties