我想创建一个继承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_ValueChanged
是EventHandler
代表。此处,组件参数值为this.AssociatedObject
。
答案 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..
}
}