【发布时间】:2020-09-27 21:01:35
【问题描述】:
我在多个 UserControl 之间绑定到同一个 ClassXSource,以使它们之间的数据同步。当 ClassXSource 发生变化时,全部触发 OnClassXSourceChanged。但这仅在整个对象发生更改时才会发生,并且当其中的字段发生更改时,我试图在所有 DependencyProperties 之间强制更新。
例子:
ClassXSource = new ClassX() { Field1 = "test" } //this will update binding in all
ClassXSource.Field1 = "test" //will not update other bindings
其中一个控件
<local:MyUserControl ClassXSource="{Binding ClassXSource, RelativeSource={RelativeSource AncestorType={x:Type local:MainUserControl}, Mode=FindAncestor}, UpdateSourceTrigger=PropertyChanged}"/>
我的用户控件
public ClassX ClassXSource
{
get { return (ClassX)GetValue(ClassXSourceProperty); }
set { SetValue(ClassXSourceProperty, value); }
}
public static readonly DependencyProperty ClassXSourceProperty =
DependencyProperty.Register("ClassXSource", typeof(ClassX), typeof(MyUserControl),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnClassXSourceChanged)));
private static void OnClassXSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//do something
}
类
public class ClassX
{
public string Field1;
public string Field2;
}
【问题讨论】:
-
为了调用 OnClassXSourceChanged 回调,属性的值必须改变。换句话说,它必须是一个新对象 - 或者临时设置空值后的旧对象。
标签: c# .net wpf dependency-properties