Sean O'Neil
Sean O'Neil

Reputation: 1241

Custom Control: How to Call Method When Inherited Dependency Property Changes?

I'm writing a custom control that inherits ItemsControl. I need to call a method whenever certain properties change. For my own dependency properties I can call this in the setter no problem, but for inherited ones like ItemsSource I don't know how to do this and I'd like to learn how without overriding the whole thing.

When searching for this I saw mention that this could be done with OverrideMetadata in WPF at least (my project is UWP). I see how OverrideMetadata is used to change the default value, but I don't see how it can be used as a property changed notification.

Upvotes: 1

Views: 664

Answers (2)

Justin XL
Justin XL

Reputation: 39006

There's a new method in UWP called RegisterPropertyChangedCallback designed just for this. For example, the following is how I remove the default entrance transition in an extended GridView control.

// Remove the default entrance transition if existed.
RegisterPropertyChangedCallback(ItemContainerTransitionsProperty, (s, e) =>
{
    var entranceThemeTransition = ItemContainerTransitions.OfType<EntranceThemeTransition>().SingleOrDefault();
    if (entranceThemeTransition != null)
    {
        ItemContainerTransitions.Remove(entranceThemeTransition);
    }
})

You can un-register using UnregisterPropertyChangedCallback.

More information can be found here.

Upvotes: 5

mm8
mm8

Reputation: 169360

For the ItemsSource property you could just override the OnItemsSourceChanged method but for any other dependency property you could use a DependencyPropertyDescriptor:

public class MyItemsControl : ItemsControl
{
    public MyItemsControl()
    {
        DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor
            .FromProperty(ItemsControl.ItemsSourceProperty, typeof(ItemsControl));
        if (dpd != null)
        {
            dpd.AddValueChanged(this, OnMyItemsSourceChange);
        }

    }

    private void OnMyItemsSourceChange(object sender, EventArgs e)
    {
        //...
    }
}

That goes for WPF. In a UWP app you should be able to use @Thomas Levesque's DependencyPropertyWatcher class: https://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/

Upvotes: 0

Related Questions