WPF如何监听BindingBase对象?

时间:2013-04-09 05:14:02

标签: c# wpf binding datatrigger

我想创建一个继承DataTrigger的特殊TriggerBase<FrameworkElement>。与DataTrigger类似,BindingBase类中定义了MyDataTrigger类型的属性。

我如何倾听它以追踪其变化?

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

1 个答案:

答案 0 :(得分:0)

好的,找到了!

考虑到这个answer,Binding不是DP。所以我试图找到Binding related 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..
    }
}