这里以 DrawingAttributes 类型的依赖属性举例。
依赖属性定义如下:
public DrawingAttributes DefaultDrawingAttributes
{
get => (DrawingAttributes)GetValue(DefaultDrawingAttributesProperty);
set => SetValue(DefaultDrawingAttributesProperty, value);
}
public static readonly DependencyProperty DefaultDrawingAttributesProperty =
DependencyProperty.Register("DefaultDrawingAttributes", typeof(DrawingAttributes), typeof(MYControl),
new FrameworkPropertyMetadata(new DrawingAttributes(), DefaultDrawingAttributesChangedCallBack) { BindsTwoWayByDefault = true });
此时在 ViewModel 中以如下方式修改 Binding 的对象属性,会发现虽然 DefaultDrawingAttributes 的值发生了改变,但是 DefaultDrawingAttributesChangedCallBack 并没有触发。(这里我用 Stylus 作为 Mvvm 框架,Fody 来自动生成 PropertyChanged 代码)
pulic class ViewModel : Screen
{
public DrawingAttributes MyDrawingAttributes { get; set; }
public void Change(){
this.MyDrawingAttributes.Width = 50;
}
}
此时会发现无论调用多少次 Change() 方法 DefaultDrawingAttributesChangedCallBack 都不会触发。
经查询发现该博文中提到
PropertyChangedCallback 只触发了一次? - 北方的河 - 博客园
https://www.cnblogs.com/northriver/p/4877837.html处理方案,其实很简单:在ViewModel中给一个新的地址(引用)
简单来说就是 new 一个新的对象,然后赋值给 ViewModel 中的 MyDrawingAttributes 就可以每次修改都触发 DefaultDrawingAttributesChangedCallBack。
pulic class ViewModel : Screen
{
public DrawingAttributes MyDrawingAttributes { get; set; }
public void Change(){
DrawingAttributes newDrawingAttributes = new DrawingAttributes();
newDrawingAttributes.Width = 50;
this.MyDrawingAttributes = newDrawingAttributes;
}
}