gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:19:37 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com