是否可以检测何时在Silverlight中的DependencyProperty上设置Xaml绑定?
E.g。如果我有一个具有单一依赖属性的自定义用户控件和一个声明如下的绑定:
public class MyControl : UserControl
{
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test",
typeof(object), typeof(MyControl),
new PropertyMetadata(null));
public object Test
{
get { return GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
}
<MyControl Test="{Binding APropInViewModel}>
</MyControl>
我可以在MyControl代码中使用这样的东西吗?
// Ctor
public MyControl()
{
TestProperty.BindingChanged += new EventHandler(...)
}
e.g。我可以收到绑定通知吗?
注意:
这是为了解决tricky order of precedence problem, described here所以只检查DependencyPropertyChanged处理程序中的新值是行不通的 - 因为属性更改处理程序不会触发!!
答案 0 :(得分:1)
此绑定中的值更改可能。您可以使用propertychanged回调方法检测更改,该方法对于依赖项属性是静态的。
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test",
typeof(object), typeof(MyControl),
new PropertyMetadata(null, TestChangedCallbackHandler));
private static void TestChangedCallbackHandler(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
MyControl obj = sender as MyControl;
Test = args.NewValue;
}
但是,这可能会导致以下事件侦听案例。如果要监听此依赖项属性的更改,请参阅此链接: Listen DepencenyProperty value changes
public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
Binding b = new Binding(propertyName) { Source = element };
var prop = System.Windows.DependencyProperty.RegisterAttached(
"ListenAttached" + propertyName,
typeof(object),
typeof(UserControl),
new System.Windows.PropertyMetadata(callback));
element.SetBinding(prop, b);
}
并像这样打电话
this.RegisterForNotification("Test", this, TestChangedCallback);