Uwp附加属性未触发属性更改回调

时间:2018-02-11 18:21:50

标签: c# xaml uwp

我定义了自定义附加属性:

 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>

侦听属性更改的方法(OnBindingsChanged)。当默认值(new List<object>())被分配给属性时,为什么它不会被触发?在目标对象已经在xaml中构建之后访问目标对象的方法是什么?

1 个答案:

答案 0 :(得分:2)

事件不会触发,因为您已将属性设置为new List<object>,因此在XAML中设置绑定时如下:

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

您只需将项目添加到现有列表中,该列表不会更改属性的实际值。 我建议用ObservableCollection替换它,然后监听CollectionChanged事件,每次添加或删除项目时都会触发该事件。