简体   繁体   中英

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.

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 .

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/

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