是的,通过绑定:
<Button Command="{Binding MyCommand}" />
如果它是一个用户控件,只需让它公开一个ICommand 类型的依赖属性。此外,MyCommand 必须在 ViewModel 内。
编辑:
假设您有一个 Button 嵌套在您的 UserControl 中:
<UserControl x:Name="MyUc">
...
<Button Command={Binding NestedCommand, ElementName=MyUc} />
...
</UserControl>
在用户控件背后的代码中,需要将“NestedCommand”作为依赖属性暴露出来:
#region NestedCommand
public ICommand NestedCommand
{
get { return (ICommand)GetValue(NestedCommandProperty); }
set { SetValue(NestedCommandProperty, value); }
}
// Using a DependencyProperty as the backing store for NestedCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NestedCommandProperty =
DependencyProperty.Register("NestedCommand", typeof(ICommand), typeof(MyUserControlClassName), new UIPropertyMetadata(MyDefaultValue));
#endregion
将“MyDefaultValue”设置为 null,将“MyUserControlClassName”设置为您的 UserControl 的名称,我们暂时称它为 Bob。
现在,当您使用该 UserControl 时,它将公开一个 NestedCommand 属性:
<Window>
...
<my:Bob NestedCommand="{Binding MyCommand}" />
...
</Window>
“my”当然是定义用户控件的 xmlns 命名空间。
并且 MyCommand 必须在您的 ViewModel 中定义,也就是您作为视图的 DataContext 放置的对象。
你可以在整个网络上找到它,但归结为创建一个实现INotifyPropertyChanged 的类,向它添加一个ICommand,然后在 Window 的构造函数中:
public MyWindow()
{
...
this.DataContext = new MyViewModel();
...
}