我正在使用MVVM模式,自定义的命令对象由ViewModel层提供。一个ViewModel对象可以通过DataContext属性连接到许多视图对象(如窗口、页面等)。在ICommand.CanExecute()中,我想检查与ViewModel命令相关的一些控件中是否存在验证错误。一个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>