views:

40

answers:

3

Hi all,

I have a dependency property on a control which is a custom class.

Now is there an event that gets raised BEFORE the value is being changed?

I know that OnPropertyChanged is raised after the property has already changed.

I need some event before so that I can cancel the changing....in order to preserve the state of the control.

I cannot set back the dependency property back to its old value as that will mean that I lose state in the control.

Thanks!

A: 

If your data objects implement INotifyPropertyChanging, then you can handle the PropertyChanging event which is raised before the property value changes.

INotifyPropertyChanging was introduced in .NET 3.5

ChrisNel52
Thanks for all the replies guys!
guest
+1  A: 

If its your DependencyProperty, you can use the ValidateValueCallback to validate the incoming value and reject it, if its not as you desire.

In the following example, only values greater than 0 will be accepted:

public int Test {
    get { return (int)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}


public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register("Test", typeof(int), typeof(YourClass), 
    new UIPropertyMetadata(0), delegate(object v) { 
      return ((int)v) > 0; // Here you can check the value set to the dp
    });
HCL
+1  A: 

You may check value of property in property declaration set section. Suppose we have CustomColor dep property:

public Color CustomColor
{
   get { return GetValue(CustomColorProperty) as Color;}

   set 
   { 
      //check value before setting
      SetValue(CustomColorProperty, value);
   }
}

Also there will be helpfull for you PropertyChangedCallback, ValidateValueCallback, CoerceValueCallback delegates.

Eugene Cheverda