David
David

Reputation: 16067

Get parent object from DependencyProperty PropertyChangedCallback

I want to execute some code each time a property is changed. The following works to some extent:

public partial class CustomControl : UserControl
{
        public bool myInstanceVariable = true;
        public static readonly DependencyProperty UserSatisfiedProperty =
            DependencyProperty.Register("UserSatisfied", typeof(bool?),
            typeof(WeeklyReportPlant), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnUserSatisfiedChanged)));


        private static void OnUserSatisfiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Console.Write("Works!");
        }
}

This prints "Works" when the value of UserSatisfiedProperty is changed. The problem is that I need to access the instance of CustomControl that is calling OnUserSatisfiedChanged to get the value of myInstanceVariable. How can I do this?

Upvotes: 4

Views: 1446

Answers (1)

Clemens
Clemens

Reputation: 128098

The instance is passed via the DependencyObject d parameter. You can cast it to your WeeklyReportPlant type:

public partial class WeeklyReportPlant : UserControl
{
    public static readonly DependencyProperty UserSatisfiedProperty =
        DependencyProperty.Register(
            "UserSatisfied", typeof(bool?), typeof(WeeklyReportPlant),
            new FrameworkPropertyMetadata(new PropertyChangedCallback(OnUserSatisfiedChanged)));

    private static void OnUserSatisfiedChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var instance = d as WeeklyReportPlant;
        ...
    }
}

Upvotes: 4

Related Questions