1

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

我怎样才能听它以追踪它的变化?

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_ValueChanged代表在哪里EventHandler。这里,组件参数值为this.AssociatedObject

4

1 回答 1

0

好的,找到了!

考虑到这个答案,Binding 不是 DP。所以我试图找到Binding相关的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..
    }
}
于 2013-04-09T09:10:09.050 回答