WPF 依赖属性的 PropertyChangedCallback 只触发一次或不触发的解决办法

8 篇文章 0 订阅

这里以 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;
      }
    
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值