Home > Back-end >  Why does PropertyChangedCallback method not execute from Dependency Property OverrideMetadata?
Why does PropertyChangedCallback method not execute from Dependency Property OverrideMetadata?

Time:05-30

I have a class called CustomGrid which derives from the Grid class. I am attempting to run a method when there are changes made to the grid's parent window's title by using OverrideMetadata on the Window class's TitleProperty. My approach to this problem, however, does not seem to work despite having another PropertyChangedCallback method I implemented, that works, using the same approach (OverrideMetadata) for the grid's MarginProperty:

public class CustomGrid : Grid
{
    static CustomGrid()
    {
        Type ownerType = typeof(CustomGrid);
        MarginProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMarginPropertyChanged)));

        Window.TitleProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(new PropertyChangedCallback(OnTitlePropertyChanged)));
    }

    private static void OnMarginPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // This executes when the grid's margin changes.
    }

    private static void OnTitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // This does not execute when the parent window's title changes.
    }
}

Why does the OnTitlePropertyChanged method not execute when the grid's parent window's title is changed? Thanks.

CodePudding user response:

The callback method is not called because you did not set the Window.Title property on a CustomGrid instance.

The expression

Window.TitleProperty.OverrideMetadata(
    typeof(CustomGrid),
    new FrameworkPropertyMetadata(OnTitlePropertyChanged));

registers the OnTitlePropertyChanged callback for the type CustomGrid. This means the callback is called whenever the dependency property is set on instances of CustomGrid, but only on those instances, not any objects like e.g. the MainWindow.

  • Related