简体   繁体   English

UWP附加属性未触发属性更改了回调

[英]Uwp attached property not firing a property changed callback

I have a custom attached property defined: 我定义了一个自定义附加属性:

 public static IList<Object> GetBindings(DependencyObject obj)
 {
    return (IList<Object>)obj.GetValue(BindingsProperty);
 }

 public static void SetBindings(DependencyObject obj, IList<Object> value)
 {
    obj.SetValue(BindingsProperty, value);
 }

 // Using a DependencyProperty as the backing store for Bindings.  This enables animation, styling, binding, etc...
 public static readonly DependencyProperty BindingsProperty =
    DependencyProperty.RegisterAttached("Bindings", typeof(IList<Object>), typeof(KeyboardInput), new PropertyMetadata(new List<Object>(), OnBindingsChanged));


 private static void OnBindingsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     Debugger.Break();
 }

Xaml: Xaml:

<TextBox x:Name="textbox" 
         PlaceholderText="Add a comment...">

    <app:KeyboardInput.Bindings> 
      <app:KeyBinding />
    </app:KeyboardInput.Bindings>

</TextBox>

And method, which listens to the property changes ( OnBindingsChanged ). 和方法,用于侦听属性更改( OnBindingsChanged )。 Why it isn't firing when the default value ( new List<object>() ) is assigned to a property? 将默认值( new List<object>() )分配给属性时,为什么不触发? What is the way to access a target object after it was already contructed in xaml? 在xaml中构造目标对象后,如何访问它?

The event won't fire because you have given the property a default value of new List<object> so in XAML when you set the binding like: 该事件不会触发,因为您已为属性指定了new List<object>的默认值,因此在XAML中设置绑定时应如下所示:

<app:KeyboardInput.Bindings> 
      <app:KeyBinding />
</app:KeyboardInput.Bindings>

you are simply just adding an item to the existing list which doesn't change the actual value of the property. 您只是将一个项目添加到现有列表中而不会更改属性的实际值。 I recommend replacing it with an ObservableCollection and then listening to the CollectionChanged event which will fire every time an item is added or removed. 我建议将其替换为ObservableCollection,然后侦听每次添加或删除项目时都会触发的CollectionChanged事件。

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

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