【发布时间】: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<object>()) 分配给属性时它没有触发?在 xaml 中已经构建目标对象后,如何访问它?
【问题讨论】:
-
永远不要将绑定更改为新对象,否则会破坏现有绑定。最好清除列表而不是创建一个新列表。
-
所以我应该只保留 null 吗?
-
我不会绑定到 null。使用空的 ObservableCollection
-
我使用了 ObservableCollection ,但属性更改回调仍然没有触发
-
我已经测试了您的代码并且属性更改回调
OnBindingsChanged确实触发了。我打电话给KeyboardInput.SetBindings(MyGrid, new List<object>());。您能否具体说明您是如何调用该方法的?