![](/img/trans.png)
[英]How to Pass HashCode of a Control as a CommandParameter in WPF XAML
[英]WPF: How to pass whole Control as CommandParameter via XAML?
我正在使用 MVVM,并且自定义 ICommand 对象由 ViewModel 层提供。 同时一个 ViewModel 对象可以通过 DataContext 属性附加到多个 View 对象(窗口、页面等)。 在 ICommand.CanExecute() 中,我想检查 View 中某些控件是否存在验证错误(附加到 ViewModel 道具,对于特定的 VM 命令很重要)。 一个 ViewModel 可以提供许多命令,每个命令都有自己的一组用于错误验证验证的控件。 因此,伪 XAML 是:
<Button.CommandParameter>
<x:Array Type="sys_win:DependencyObject">
<sys_win:DependencyObject>
<reference_to_textbox_or_other_control/>
</sys_win:DependencyObject>
<sys_win:DependencyObject>
<reference_to_textbox_or_other_control/>
</sys_win:DependencyObject>
</x:Array>
</Button.CommandParameter>
第二个问题是特定命令可能会被控件调用,控件本身是用于集合项的 DataTemplate 的一部分(在我的情况下 - ListBoxItem 数据模板的一部分)。 我的模板化列表框项目有两个文本框(绑定到相应 ViewModel 的两个道具)和按钮,它们调用 ViewModel 命令。 因此,在命令 CanExecute() 中,我需要检查某些窗口控件和两个文本框的验证错误,它们属于此列表项,而不是其他项。 如果我想将 ListBoxItem.IsSelected 属性作为 CommandParameter 传递,下面的代码工作正常:
<Button DataContext="{Binding}"
Command="{Binding Path=SwitchCommand}"
CommandParameter="{Binding Path=IsSelected, RelativeSource={
RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}}}"/>
但是如何将整个 (DependencyObject)ListBoxItem 作为 CommandParameter 传递? 在第一个代码示例中,这个通过 {Binding RelativeSource} 传递的 ListBoxItem 如何与其他当前窗口控件混合?
非常抱歉,如何在 xaml 中添加对控件的引用?
<Button.CommandParameter>
<x:Array Type="sys_win:DependencyObject">
<sys_win:DependencyObject>
<reference_to_textbox_or_other_control/>
</sys_win:DependencyObject>
<sys_win:DependencyObject>
<reference_to_textbox_or_other_control/>
</sys_win:DependencyObject>
</x:Array>
</Button.CommandParameter>
只需使用没有Path
的绑定:
<Button DataContext="{Binding}"
Command="{Binding Path=SwitchCommand}"
CommandParameter="{Binding RelativeSource=
{RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}}}"/>
我不确定我是否正确阅读了您的示例,但它似乎违反了 MVVM 原则。 (如果我读错了,我很抱歉)。
MVVM 背后的想法是将视图模型与对 XAML/视图实体的任何依赖解耦。 您通过让 CommandParameter 依赖于用户控件来打破这一点。 我要做的是在 ViewModel 中创建状态属性并将用户控件验证绑定到这些状态,然后在 CanExecute 中您可以测试这些属性的值,而不是尝试绑定到用户控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.