我正在尝试使用自定义类在 XAML 中传递多个 CommandParameters。
我创建了一个名为 ValueCommandArgs 的类,它继承自 DependencyObject 并且有两个 DepencyProperties(我们称它们为 Value1 和 Value2 对于这个例子)。
应该调用命令并传递此对象的按钮如下所示:
<Button Command="{Binding ChangeValueCommand}" Content="Execute Command">
<Button.CommandParameter>
<args:ValueCommandArgs Value1="{Binding TestValue1}" Value2="{Binding TestValue2}" />
</Button.CommandParameter>
</Button>
我在我的命令中确实得到了一个 ValueCommandArgs-Object 作为参数,但是属性 Value1 和 Value2 总是 null/empty。
我知道这可以通过 MultiBinding 和 Converter 来解决,但我认为我尝试的方式会是一种更简洁的方法。
为什么这行不通?
最佳答案
Binding
需要一个源对象才能提供一个值。当未指定绑定(bind)源时(使用 Source
或 ElementName
等)例如:Value1="{Binding TestValue1}"
使用元素的 DataContext
。
args:ValueCommandArgs
对象不从 Button
元素继承 DataContext
,因为属性值继承特别是关于属性值如何继承根据元素树中的父子关系从一个元素到另一个元素。
按钮对象不在其逻辑树或可视树中包含 CommandParameter
属性的值。
在许多情况下,可以通过将值直接绑定(bind)到 ViewModel 来避免需要具有多个绑定(bind)值的 CommandParameter
。
当无法避免时,您可以使用不同类型的绑定(bind)标记扩展,例如:https://github.com/JohanLarsson/Gu.Reactive#ninjabinding它将使用根 FrameworkElement
作为绑定(bind)源。
另一种方法是此博客文章中所示的绑定(bind)代理技术:How to bind to data when the DataContext is not inherited
关于c# - 绑定(bind)不适用于在 XAML 中创建的 DependencyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26364979/