WPF 选择了菜单上的项或获取视图模型中的命令参数



我正在寻找几个小时来解决一个简单的问题。我想在我的菜单上使用"SelectedItem",但经过几个小时的堆栈溢出,我发现这是不可能的。我找到了很多关于"命令参数"的信息,但我不明白它是如何工作的。 这就是我想做的:我有一个带有"背景1,背景2,..."的菜单。如果您在菜单中选择背景,我想将该选定的背景设置为背景。

这是一个学校项目,所以我们必须使用 MVVM,不允许使用任何代码隐藏。 如何在视图模型中"使用"命令参数?

这是我的主窗口.xaml:

<Toolbar>
<Menu>
<MenuItem Header="Background" ItemsSource="{Binding Backgrounds}">
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem Header="{Binding Name}" Command="{Binding ChangeBackgroundCommand}" CommandParameter="{Binding Name}"/>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</Menu>
</Toolbar>

这是我的主窗口视图模型的一部分:

public MainWindowViewModel()
{
//load data
BackgroundDataService bds = new BackgroundDataService();
Backgrounds = bds.GetBackgrounds();
//connect command
WijzigBackgroundCommand = new BaseCommand(WijzigBackground);
}
private void ChangeBackground()
{
//I want here the name of the selected menuItem (by parameter?)
}

}

我们使用baseCommand类(我不想改变这个类,因为我认为它是标准):

class BaseCommand : ICommand
{
Action actie;
public BaseCommand(Action Actie)
{
actie = Actie;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
actie.Invoke();
}
}

我经常使用堆栈溢出:-)这是我的第一篇文章/问题,我希望很清楚

试试这个:

class BaseCommand<T> : ICommand
{
private readonly Action<T> _executeMethod = null;
private readonly Func<T, bool> _canExecuteMethod = null;
public BaseCommand(Action<T> executeMethod)
: this(executeMethod, null)
{
}
public BaseCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
{
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
public bool CanExecute(T parameter)
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod(parameter);
}
return true;
}
public void Execute(T parameter)
{
if (_executeMethod != null)
{
_executeMethod(parameter);
}
}
public event EventHandler CanExecuteChanged;
bool ICommand.CanExecute(object parameter)
{
if (parameter == null &&
typeof(T).IsValueType)
{
return (_canExecuteMethod == null);
}
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
}

像这样使用它:

public MainWindowViewModel()
{
// ...
// connect command
WijzigBackgroundCommand = new BaseCommand<YourBackgroundClass>(
(commandParam) => WijzigBackground(commandParam), 
(commandParam) => CanWijzigBackground(commandParam));
}
private void WijzigBackground(YourBackgroundClass param)
{
// Use 'param'
}
private bool CanWijzigBackground(YourBackgroundClass param)
{
// Use 'param'
}

最新更新