是的,通过绑定可以实现:
<Button Command="{Binding MyCommand}" />
如果它是一个用户控件,只需使其公开类型为
ICommand
的依赖属性。此外,MyCommand必须在ViewModel中。
编辑:
假设您在UserControl中嵌套了一个
Button
:
<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); }
}
public static readonly DependencyProperty NestedCommandProperty =
DependencyProperty.Register("NestedCommand", typeof(ICommand), typeof(MyUserControlClassName), new UIPropertyMetadata(MyDefaultValue));
#endregion
将"MyDefaultValue"设置为null,并将"MyUserControlClassName"设置为您的用户控件名称,我们称其为Bob。
现在当您使用该用户控件时,它将公开一个NestedCommand属性:
<Window>
...
<my:Bob NestedCommand="{Binding MyCommand}" />
...
</Window>
"my"是定义您的UserControls的xmlns命名空间。
而MyCommand必须在您的ViewModel中定义,即您放置为视图DataContext的对象。
您可以在网上找到有关此的所有信息,但归结为创建实现INotifyPropertyChanged
的类,向其中添加一个ICommand
,然后在窗口构造函数中:
public MyWindow()
{
...
this.DataContext = new MyViewModel();
...
}