从DependencyProperty PropertyChangedCallback获取父对象

本文关键字:对象 获取 PropertyChangedCallback DependencyProperty | 更新日期: 2023-09-27 18:02:04

我想在每次更改属性时执行一些代码。以下内容在一定程度上起作用:

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!");
        }
}

当UserSatisfiedProperty的值被改变时,打印"Works"。问题是,我需要访问CustomControl的实例,调用OnUserSatisfiedChanged来获取myinstancvariable的值。我该怎么做呢?

从DependencyProperty PropertyChangedCallback获取父对象

通过DependencyObject d参数传递实例。您可以将其强制转换为您的WeeklyReportPlant类型:

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;
        ...
    }
}