开发者

Dependency property callback does not work

开发者 https://www.devze.com 2023-03-17 23:07 出处:网络
I have the following code: private static readonly DependencyProperty IDProperty = DependencyProperty.Register(

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 som开发者_JAVA技巧ething here!  
    }

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

Why?


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.


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.


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)));
0

精彩评论

暂无评论...
验证码 换一张
取 消