命令的目的是将生成命令的代码与执行命令的代码解耦。因此:如果您想要紧密耦合,最好通过事件:
<UserControl ... x:Class="myclass">
...
<Button Click="myclass_find" .../>
...
</UserControl>
对于松耦合,需要添加
CommandBinding
UserControl
:
<UserControl ... >
<UserControl.DataContext>
<local:MyViewModel/>
</UserControl.DataContext>
<UserControl.CommandBindings>
<Binding Path="myFindCommandBindingInMyViewModel"/>
</UserControl.CommandBindings>
...
<Button Command="ApplicationComamnd.Find" .../>
...
</UserControl>
(不确定语法)
或者你可以添加一个
给你的
用户控件
的
CommandBindings
在构造函数中,从ViewNodel获取值:
partial class MyUserControl : UserControl
{
public MyUSerControl()
{
InitializeComponent();
CommandBinding findCommandBinding =
((MyViewModel)this.DataContext).myFindCommandBindingInMyViewModel;
this.CommandBindings.Add(findCommandBinding);
}
}