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

C# 内部字段更改时强制对DependencyProperty进行绑定更新,c#,.net,wpf,dependency-properties,C#,.net,Wpf,Dependency Properties,我在多个UserControls之间绑定到同一个ClassXSource,以使它们之间的数据保持同步。当ClassXSource在一个中更改时,OnClassXSourceChanged在所有中被触发。但是,只有当完整对象的属性发生更改时,才会发生这种情况,并且当其中的字段发生更改时,我尝试在所有DependencyProperties之间强制更新 例如: ClassXSource = new ClassX() { Field1 = "test" } //this will update bin

我在多个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}"/>
阶级


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

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


请注意,无论哪种方式,这只适用于项目,而不适用于字段。如果要绑定到属性,则必须将
Field1
Field2
更改为属性,或在其上添加属性。

为了调用OnClassXSourceChanged回调,属性的值必须更改。换句话说,它必须是一个新对象,或者临时设置空值后的旧对象。这不是真的。在ClassX中实现INotifyPropertyChanged不会更新ClassXSource属性的绑定。@Clemens为True,但会更新绑定到当前
ClassXSource
的Changed属性的所有对象,这应该足以保持所有内容的同步。它不会这样做。控件至少必须在其OnClassXSourceChanged回调中将PropertyChanged事件处理程序附加到ClassX实例。@Clemens啊,我刚刚回顾了这个问题。我以为他是在约束
ClassX
的项目。你说得对,看起来他必须倾听事件的变化。
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;
}