简体   繁体   English

Silverlight检测Dependency属性何时具有Xaml绑定

[英]Silverlight detect when Dependency property has a Xaml binding

Is it possible to detect when a Xaml binding is set on a DependencyProperty in Silverlight? 是否可以检测何时在Silverlight中的DependencyProperty上设置了Xaml绑定?

Eg if I had a custom user-control with single dependency property and a binding declared like this: 例如,如果我有一个具有单个依赖项属性的自定义用户控件,并且声明了这样的绑定:

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>

Can I in the MyControl code to something like this? 我可以在MyControl代码中输入类似的内容吗?

// Ctor
public MyControl()
{ 
    TestProperty.BindingChanged += new EventHandler(...)
} 

eg can I get a notification of binding? 例如,我可以收到绑定通知吗?

NOTE: 注意:

This is to solve a tricky order of precedence problem, described here so just checking for new values in the DependencyPropertyChanged handler won't work - because the property changed handler doesn't fire!! 这是为了解决一个棘手的优先级问题,在此进行描述,因此仅检查DependencyPropertyChanged处理程序中的新值将不起作用-因为更改后的属性处理程序不会触发!

It is possible for value changes in this binding. 此绑定中的值可能会更改。 You can detect changes using propertychanged callback method which is static for Dependency properties. 您可以使用propertychanged回调方法(对于Dependency属性是静态的)检测更改。

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; 
    }

However, this might cause following event listening cases. 但是,这可能会导致以下事件侦听情况。 If you want to listen changes on this dependency property is explained in this link : Listen DepencenyProperty value changes 如果您想监听此依赖项属性的更改,请参见以下链接: 监听DepencenyProperty值的更改

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);
    }

and call like this 像这样打电话

this.RegisterForNotification("Test", this, TestChangedCallback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM