Dependency property callback does not work

╄→гoц情女王★ 提交于 2019-12-11 03:05:51

问题


I have the following code:

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!  
    }

I can see that when I change ID, the line SetValue(IPproperty is called), but it doesn't call the IDChanged.

Why?


回答1:


Your code is correct, however PropertyChanged callback will not be called until it has changed. Try changing the property to two different values in consecutive lines of code and have a break point you can see that it's been hit. I believe it's set to -1 and hence it isn't called.




回答2:


Make the DP public static readonly. When setting the value in XAML, the wrapper is not used, the DP is used directly. So, it has to be public.

But...apparently you are setting it from within code? In that case, i don't know what's wrong...but you can always try.




回答3:


I don't know if this was ever solved or not but if you are setting the value in the XAML file that uses it, there are certain circumstances where the proceedural code default value will take precedent and it will never fire from being set in the XAML initially. So remove the default value of -1 so

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

becomes

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


来源:https://stackoverflow.com/questions/6584463/dependency-property-callback-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!