简体   繁体   中英

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!

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM