在我的 xaml 代码中,我有一个包含以下项目的菜单:
<Menu x:Name="menu" Grid.Row="0" Background="Transparent" HorizontalAlignment="Right">
<MenuItem Header="Root">
<MenuItem Header="Sub1" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
<MenuItem Header="Sub2" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
<MenuItem Header="Sub3" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
<MenuItem Header="Sub4" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
<MenuItem Header="Sub5" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
<MenuItem Header="Sub6" Command="{Binding Command}" CommandParameter="{Binding ???}"></MenuItem>
</MenuItem>
</Menu>
Command 是 ICommand 类型的属性。实现是
public class RelayCommand : ICommand
{
private readonly Action<object> execute;
private readonly Predicate<object> canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
public void Execute(object parameter)
{
this.execute(parameter);
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
在我的视图模型的构造函数中,我有一行:
this.Command = new RelayCommand(OnMenuItemExecute);
OnMenuItemExecute 的方法是:
private void OnMenuItemExecute(object parameter)
{
// Here i want to know which menuitem executed the command
}
我只是不知道我应该作为命令参数传递什么