2013-04-09 62 views
1

我想創建一個繼承TriggerBase<FrameworkElement>的特殊DataTrigger。與DataTrigger類似,MyDataTrigger類中定義了BindingBase類型的屬性。WPF如何聆聽BindingBase對象?

我怎樣才能聽到它的變化?

public class MyDataTrigger : TriggerBase<FrameworkElement> 
{ 
    ... 

    /// <summary> 
    /// [Wrapper property for BindingProperty] 
    /// <para> 
    /// Gets or sets the binding that produces the property value of the data object. 
    /// </para> 
    /// </summary> 
    public BindingBase Binding 
    { 
     get { return (BindingBase)GetValue(BindingProperty); } 
     set { SetValue(BindingProperty, value); } 
    } 

    public static readonly DependencyProperty BindingProperty = 
     DependencyProperty.Register("Binding", 
            typeof(BindingBase), 
            typeof(MyDataTrigger), 
            new FrameworkPropertyMetadata(null)); 

} 

更新:

的主要問題是,我不知道如何找到BindingBase相關DependencyProperty。我知道如何傾聽DP;

void ListenToDP(object component, DependencyProperty dp) 
{ 
    DependencyPropertyDescriptor dpDescriptor = DependencyPropertyDescriptor.FromProperty(dp, component.GetType()); 
    dpDescriptor.AddValueChanged(component, DPListener_ValueChanged); 
} 

DPListener_ValueChangedEventHandler委託。在這裏,組件參數值是this.AssociatedObject

+0

難道說,'BindingBase'相關DP總是'DataContext'? – Mimi 2013-04-09 06:23:57

回答

0

好的,找到了!考慮到answer,綁定不是DP。所以,我試圖找到綁定關聯DP:

Type type = Binding.GetType(); 
PropertyPath propertyPath = (PropertyPath)(type.GetProperty("Path").GetValue(Binding)); 
string propertyName = propertyPath.Path; 

完整代碼:

public class MyDataTrigger : TriggerBase<FrameworkElement> 
{ 
    ... 

    public BindingBase Binding 
    { 
     get; 
     set; 
    } 

    protected override void OnAttached() 
    { 
     base.OnAttached(); 

     if (Binding != null && this.AssociatedObject.DataContext != null) 
      // 
      // Adding a property changed listener.. 
      // 
      Type type = Binding.GetType(); 
      PropertyPath propertyPath = (PropertyPath)(type.GetProperty("Path").GetValue(Binding)); 
      string propertyName = propertyPath.Path; 

      TypeDescriptor.GetProperties(this.AssociatedObject.DataContext).Find(propertyName, false).AddValueChanged(this.AssociatedObject.DataContext, PropertyListener_ValueChanged); 
    } 

    private void PropertyListener_ValueChanged(object sender, EventArgs e) 
    { 
     // Do some stuff here.. 
    } 
} 
+0

這不能被標記爲一般答案。這裏僅考慮了「BindingBase」的'Path'屬性。 (並且例如不是'XPath')。任何建議? – Mimi 2013-04-12 17:11:04

+0

使用什麼錯誤... var propertyName =((Binding)this.Binding).Path.Path; – midspace 2013-12-08 04:48:41