我正在寻找几个小时来解决一个简单的问题。我想在我的菜单项上使用“SelectedItem”,但经过几个小时的 stackoverflow 我发现这是不可能的。我发现了很多关于“CommandParameter”的信息,但我不明白它是如何工作的。
这就是我想做的:我有一个带有“background1,background2,...”的菜单。如果您在菜单中选择背景,我想将所选背景设置为背景。
这是一个学校项目,所以我们必须使用 MVVM 并且不允许使用代码隐藏。
如何在 ViewModel 中“使用”Commandparameter?
这是我的 mainWindow.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>
这是我的 mainWindowViewModel 的一部分:
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();
}
}
我经常使用 stackoverflow :-) 这是我的第一篇文章/问题,我希望它很清楚