【问题标题】:WPF How to listen to a BindingBase object?WPF 如何监听 BindingBase 对象?
【发布时间】:2013-04-09 05:14:01
【问题描述】:

我想创建一个特殊的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 代表。此处,component 参数值为this.AssociatedObject

【问题讨论】:

  • BindingBase关联的DP总是DataContext是真的吗?

标签: c# wpf binding datatrigger


【解决方案1】:

好的,找到了!

考虑到这个answer,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..
    }
}

【讨论】:

  • 这不能被标记为一般答案。这里只考虑BindingBasePath 属性。 (例如不是XPath)。有什么建议吗?
  • 使用有什么问题... var propertyName = ((Binding)this.Binding).Path.Path;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
相关资源
最近更新 更多