2013-03-02 42 views
3

我想在每次更改属性时执行一些代码。以下作品在一定程度上:从DependencyProperty获取父对象PropertyChangedCallback

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的值。我怎样才能做到这一点?

回答

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