Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf Dependency property before changing event?

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!

like image 949
guest Avatar asked Feb 04 '26 04:02

guest


2 Answers

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
    });
like image 55
HCL Avatar answered Feb 05 '26 18:02

HCL


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

like image 35
ChrisNel52 Avatar answered Feb 05 '26 18:02

ChrisNel52