【问题标题】:Dependency property callback does not work依赖属性回调不起作用
【发布时间】:2011-07-05 14:38:16
【问题描述】:

我有以下代码:

private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
           "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged)));

    public int ID
    {
        get { return (int)GetValue(IDProperty); }
        set { SetValue(IDProperty, value); }
    }

    private static void IDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
         // Do something here!  
    }

我可以看到,当我更改 ID 时,行 SetValue(IPproperty is called),但它没有调用 IDChanged。

为什么?

【问题讨论】:

    标签: wpf dependency-properties


    【解决方案1】:

    您的代码是正确的,但是在更改之前不会调用 PropertyChanged 回调。尝试在连续的代码行中将属性更改为两个不同的值,并设置一个断点,您可以看到它已被击中。我相信它被设置为 -1,因此它没有被调用。

    【讨论】:

    • 有点问题,我无法让它第一次触发,所以我将依赖属性默认设置为非标准值,强制它引发回调。
    【解决方案2】:

    使 DP 公共静态只读。在 XAML 中设置值时,不使用包装器,直接使用 DP。所以,它必须是公开的。

    但是...显然您是在代码中设置它?在那种情况下,我不知道出了什么问题……但是您可以随时尝试。

    【讨论】:

      【解决方案3】:

      我不知道这是否曾经解决过,但如果您在使用它的 XAML 文件中设置值,在某些情况下,程序代码默认值将成为先例,并且永远不会触发最初在 XAML 中设置。所以去掉-1这样的默认值

      private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
                 "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata(-1, new PropertyChangedCallback(IDChanged)));
      

      变成

      private static readonly DependencyProperty IDProperty = DependencyProperty.Register(
             "ID", typeof(int), typeof(DetailDataControl), new PropertyMetadata( new PropertyChangedCallback(IDChanged)));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 2016-09-06
        • 1970-01-01
        • 2019-12-14
        • 2013-03-06
        • 2017-07-19
        相关资源
        最近更新 更多