找到了一种以我尝试的方式解决它的方法。在这里留下答案,以便人们可以使用它:
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 属性并进行相应的配置:
public ICommand ViewModelCommand { get; set; }
public ViewModelConstructor()
{
ViewModelCommand = new DelegateCommand(ViewModelCommandExecute);
}
private void ViewModelCommandExecute()
{
// Do something
}
4) 最后,在嵌套 UserControl 的 View 上,我们声明绑定:
<UserControls:UserControl Command={Binding ViewModelCommand}/>
这样,绑定就会发生,您可以将任何用户控件的按钮中的命令绑定到您的 ViewModel,而不会破坏 MVVM。