【问题标题】:Force binding update on DependencyProperty when internal field changes内部字段更改时强制对 DependencyProperty 进行绑定更新
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 这不是真的。在 ClassX 中实现 INotifyPropertyChanged 不会更新 ClassXSource 属性的绑定。
  • @Clemens 是的,但它会更新绑定到当前ClassXSource 的更改属性的所有对象,这足以使所有内容保持同步。
  • 它完全不会那样做。控件至少必须在其 OnClassXSourceChanged 回调中将 PropertyChanged 事件处理程序附加到 ClassX 实例。
  • @Clemens 啊,我只是回顾一下这个问题。我以为他绑定了ClassX 的属性。你是对的,看起来他必须监听事件的变化。
猜你喜欢
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 2011-07-25
  • 2011-02-09
  • 2017-06-13
  • 2019-09-23
  • 1970-01-01
相关资源
最近更新 更多