Silverlight检测依赖属性何时具有XAML结合



是否可以检测何时在Silverlight中的依赖项上设置XAML绑定?

例如。如果我有一个具有单个依赖性属性的自定义用户控制,则声明这样的绑定:

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(...)
} 

例如。我可以收到约束力的通知吗?

注意:

这是解决此处描述的棘手优先问题的棘手顺序,因此仅检查依赖项properpertychanged处理程序中的新值无法使用 - 因为属性更改了处理程序不会发射!

可能会在此绑定中进行价值变化。您可以使用属性换回的回调方法检测更改,该回调方法是依赖性属性的静态。

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

但是,这可能会导致事件聆听案例。如果您想收听此依赖项属性的更改,则在此链接中说明:收听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);
    }

和这样的呼叫

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

最新更新