【问题标题】:Uwp attached property not firing a property changed callbackUwp 附加属性未触发属性更改回调
【发布时间】:2018-07-21 22:30:24
【问题描述】:

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

 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 方法,它监听属性变化 (OnBindingsChanged)。为什么将默认值 (new List&lt;object&gt;()) 分配给属性时它没有触发?在 xaml 中已经构建目标对象后,如何访问它?

【问题讨论】:

  • 永远不要将绑定更改为新对象,否则会破坏现有绑定。最好清除列表而不是创建一个新列表。
  • 所以我应该只保留 null 吗?
  • 我不会绑定到 null。使用空的 ObservableCollection
  • 我使用了 ObservableCollection ,但属性更改回调仍然没有触发
  • 我已经测试了您的代码并且属性更改回调OnBindingsChanged 确实触发了。我打电话给KeyboardInput.SetBindings(MyGrid, new List&lt;object&gt;());。您能否具体说明您是如何调用该方法的?

标签: c# xaml uwp


【解决方案1】:

该事件不会触发,因为您已为属性提供了默认值 new List&lt;object&gt;,因此在 XAML 中设置绑定时如下:

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

您只是将一个项目添加到现有列表中,而不会更改属性的实际值。 我建议将其替换为 ObservableCollection,然后监听 Co​​llectionChanged 事件,该事件将在每次添加或删除项目时触发。

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 2014-06-14
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多