当内部字段更改时,对DependencyProperty进行强制绑定更新

问题描述 投票:0回答:1

我绑定到多个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;
}
c# .net wpf dependency-properties
1个回答
-1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.