【问题标题】:Data binding dependency property to data object数据绑定依赖属性到数据对象
【发布时间】: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


【解决方案1】:

更改 DataSource 上的 IsTrue 属性对 依赖对象类

我猜你的结论是,DependencyObjectClass.BooleanValue 属性设置器从未被调用过。事实上 WPF 并没有这样做。而是直接设置依赖属性的值,就像直接调用SetValue一样。

请参阅 Checklist for Defining a Dependency PropertyImplications for Custom Dependency Properties 了解说明。

为了获得有关更改的依赖项属性值的通知,您必须在 DependencyProperty.Register 中使用依赖项属性元数据注册一个 PropertyChangedCallback

【讨论】:

  • 谢谢!我没有想到要检查值而不是只看它的访问器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多