c# - 数据绑定(bind)依赖属性到数据对象

标签 c# .net wpf data-binding dependency-properties

我有一个带有 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;
}

我试图用这段代码绑定(bind)上面的两个对象:

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 都会使用react,但它不会以相反的方式工作(更改 DataSource 的 IsTrue 属性对 DependencyObjectClass 没有任何作用)。

我做错了什么?我必须手动处理 OnPropertyChanged 事件吗?如果是,那将有点令人失望,因为我希望这会自动完成。

最佳答案

changing IsTrue property on DataSource does nothing for DependencyObjectClass

我猜您是根据从未调用过 DependencyObjectClass.BooleanValue 属性 setter 这一事实得出结论的。事实上 WPF 并没有这样做。相反,它直接设置依赖属性的值,就像直接调用 SetValue 一样。

参见 Checklist for Defining a Dependency PropertyImplications for Custom Dependency Properties寻求解释。

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

关于c# - 数据绑定(bind)依赖属性到数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070780/

相关文章:

c# - WPF 中的 Application MainWindow 为空(使用 Caliburn Micro)

c# - 组合框项目源 = ObservableCollection & 我需要在顶部有一个 '-None-' 虚拟条目

c# - 将类添加到 Blazor(Razor) 验证

c# - 在异步代码中调试异常

c# - 设计我的模型以绑定(bind)到 DataGrid 项目和标题

c# - 禁用最小化按钮,但保留交叉和最大化按钮 - WPF、C#

c# - Greybox GB_showcenter 不显示弹出窗口

c# - HttpListener 将数据写入响应输出流

c# - Xamarin + WCF + SSL + 传输 + 证书

c# - 类型化和非类型化数据集的 LINQ 和性能?