找到了一种解决方法,就是我一直在尝试的方式。 在这里留下答案,以便人们可以使用:
1)在您的用户控件的代码后台中,创建一个依赖属性。 我选择了ICommand,因为在我的ViewModel中将其设置为DelegateCommand:
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(UserControl));
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
2) 在您的UserControl的XAML代码中,将此依赖属性(在本例中为按钮)进行绑定:
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
<Button Command="{Binding Command}" />
</Grid>
3) 接下来,在您的ViewModel上声明一个Command属性,并进行相应的配置:
3) Next, 在您的ViewModel上声明一个Command属性,并进行相应的配置:
public ICommand ViewModelCommand { get; set; }
public ViewModelConstructor()
{
ViewModelCommand = new DelegateCommand(ViewModelCommandExecute);
}
private void ViewModelCommandExecute()
{
}
4)最后,在嵌套了UserControl的View中,我们声明绑定:
<UserControls:UserControl Command={Binding ViewModelCommand}/>
通过这种方式,绑定将会发生,您可以将任何用户控件按钮的命令绑定到您的ViewModels上,而不会破坏MVVM。