内部字段更改时,在DependencyProperty上强制绑定更新

时间:2020-06-08 19:28:39

标签: c# .net wpf dependency-properties

我绑定到多个UserControl之间的同一ClassXSource,以使它们之间的数据同步。当ClassXSource更改为1时,将全部触发OnClassXSourceChanged。但这仅在更改了完整的对象时才会发生,并且当范围内的字段发生更改时,我试图在所有DependencyProperty之间强制更新。

示例:

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}"/>

MyUserControl

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;
}

1 个答案:

答案 0 :(得分:-1)

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

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

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