从DependencyProperty PropertyChangedCallback获取父对象

4

我希望每次属性改变时都能执行一些代码。以下代码在某种程度上可以实现:

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”。问题是,我需要访问调用OnUserSatisfiedChanged的CustomControl实例,以获取myInstanceVariable的值。我该怎么做?

1个回答

4
实例通过 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;
        ...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接