c# - 内部字段更改时强制对 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;
}
解决方案
ClassX
需要实施变更通知。通过实现INotifyProeprtyChanged
(或使用依赖属性),绑定到的对象ClassX
将收到更改通知,并且绑定将正确更新。
如果您没有绑定到的属性ClassX
并且想要直接在代码隐藏中处理属性更改,则可以将处理程序附加到PropertyChanged
事件。您可以在OnClassXSourceChanged
方法中执行此操作。
请注意,无论哪种方式,这仅适用于proeprties,而不适用于字段。如果要绑定到它们,则必须更改Field1
并Field2
进入属性,或在它们之上添加属性。
推荐阅读
- mysql - 将字符集从 latin2_bin 更改为 utf8 并删除所有以“特殊”字符开头的数据
- python - 来自条目文本字段的 Tkinter get()
- php - 在使用 Eloquent 上传到数据库之前检查模型属性是否已经存在,性能问题
- angular - Ionic 项目仅在使用 --prod 构建时引发错误
- sql - 此代码中的 IF 语句有什么问题?
- vuetify.js - 图像未从 vuetify 上 v-img 上的 url 加载
- .net - 使用 axios.post 发送防伪令牌时出现 400 错误
- python - 如何保护 Python 源代码,同时使文件可运行?
- reactjs - 无法在反应应用程序中动态加载图像
- r - 在 R 4.0.0 之前安装了包“xxx”:请重新安装它(已经完成全新安装并检查了 lib 路径)