首页 > 解决方案 > 内部字段更改时强制对 DependencyProperty 进行绑定更新

问题描述

我绑定到多个 UserControls 之间的同一个 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;
}

标签: c#.netwpfdependency-properties

解决方案


ClassX需要实施变更通知。通过实现INotifyProeprtyChanged(或使用依赖属性),绑定到的对象ClassX将收到更改通知,并且绑定将正确更新。

如果您没有绑定到的属性ClassX并且想要直接在代码隐藏中处理属性更改,则可以将处理程序附加到PropertyChanged事件。您可以在OnClassXSourceChanged方法中执行此操作。

请注意,无论哪种方式,这仅适用于proeprties,而不适用于字段。如果要绑定到它们,则必须更改Field1Field2进入属性,或在它们之上添加属性。


推荐阅读