2013-03-02 41 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; 
     ... 
    } 
}