简体   繁体   中英

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:

<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 ). Why it isn't firing when the default value ( new List<object>() ) is assigned to a property? What is the way to access a target object after it was already contructed in 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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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