从DependencyProperty PropertyChangedCallback获取父对象

时间:2013-03-02 11:21:46

标签: c# .net wpf dependency-properties

我希望每次更改属性时都执行一些代码。以下工作在某种程度上起作用:

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 个答案:

答案 0 :(得分:3)

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