Luk*_*uke 5 c# wpf xaml binding
我尝试使用自定义类在 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>
Run Code Online (Sandbox Code Playgroud)
我确实在命令中获得了一个 ValueCommandArgs-Object 作为参数,但是属性Value1和Value2 始终为 null/empty。
我知道这可以通过 MultiBinding 和 Converter 来解决,但我认为我尝试的方法将是一种更干净的方法。
为什么这不起作用?
ABinding
需要一个源对象才能提供值。当未指定绑定源时(使用Source
或ElementName
等),例如:使用元素的Value1="{Binding TestValue1}"
。DataContext
该args:ValueCommandArgs
对象不会DataContext
从Button
元素继承,因为属性值继承特别涉及属性值如何根据元素树中的父子关系从一个元素继承到另一个元素。
CommandParameter
按钮对象在其逻辑树和可视树中都不包含该属性的值。
CommandParameter
在许多情况下,可以通过将值直接绑定到 ViewModel 来避免需要具有多个绑定值的情况。
当无法避免时,您可以使用不同类型的绑定标记扩展,例如: https: //github.com/JohanLarsson/Gu.Reactive#ninjabinding,它将使用根FrameworkElement
作为绑定的源。
另一种方法是本博客文章中所示的绑定代理技术:How to bind to data when the DataContext is notherited
归档时间: |
|
查看次数: |
1069 次 |
最近记录: |