Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to DependencyProperty changed event and get the old value

I have the following code to subscribe to property changed event for VisiblePosition property of Column class:

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ColumnBase.VisiblePositionProperty, typeof(Column));

if (dpd != null)
{
   dpd.AddValueChanged(col, ColumnVisiblePositionChangedHandler);
}

Here is the definition of the ColumnVisiblePositionChangedHandler method:

static internal void ColumnVisiblePositionChangedHandler(object sender, EventArgs e)

The problem is I need to get the old value of the property. How do I do that?

Thanks,

like image 701
sean717 Avatar asked Jan 11 '12 23:01

sean717


2 Answers

Unfortunately, you don't get old value information when registering property changed event handler this way.

One workaround is to store property value somewhere (this is your 'old' value) and then compare it to current value in the event handler.

Another workaround is to create your own dependency property (DP) and create binding between your DP and the control's DP. This will give you change notification in the WPF style.

Here is an article about this.

like image 65
Libor Avatar answered Nov 15 '22 20:11

Libor


You can do that when you register your dependency property in the attached event handler. Please find below the syntax for a dependency property and how to get the old value on PropertyChanged event handler:

//Declaration of property
public static readonly DependencyProperty MyNameProperty =
    DependencyProperty.Register("MyName",
                                typeof(PropertyType),
                                typeof(ClassName),
                                new PropertyMetadata(null,
                                new PropertyChangedCallback(MyNameValueChanged)));

//PropertyChanged event handler to get the old value
private static void MyNameValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
{
    object oldValue = eventArgs.OldValue; //Get the old value
}
like image 32
VSS Avatar answered Nov 15 '22 19:11

VSS