3

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?

Drake
  • 8,225
  • 15
  • 71
  • 104
mans
  • 17,104
  • 45
  • 172
  • 321

3 Answers3

7

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.

anivas
  • 6,437
  • 6
  • 37
  • 45
  • Bit of a gotcha, I couldn't get it to fire first time round so I set the dependency property default to a non standard value forcing it to raise the callback. – Moon Waxing Feb 09 '17 at 02:48
0

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)));
noone392
  • 1,624
  • 3
  • 18
  • 30
0

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.

rvandaal
  • 36
  • 1