我想知道如何从菜单中获取“选定的”菜单项。 基本上,我想获取“选定的”菜单项,以便可以对列表框进行排序。 这是我的菜单 XAML。
<Menu>
<MenuItem Header="Sort by" ItemsSource="{Binding SortByOptions}"
*SelectedItem="{Binding GroupBy}"*/>
</Menu>
我用菜单切换了组合框,但在菜单中,“SelectedItem”并不像组合框中那样存在。我想知道如何获得从菜单中选择的项目。
C#
ItemsSource 绑定(bind)“SortByOptions”是一个包含要排序的选项的字符串 ObservableCollection。 绑定(bind)“GroupBy”是一个字符串,每次用户选择另一个菜单项时都会设置该字符串。
我正在搜索每次用户选择另一个菜单项时设置变量“GroupBy”。
以前,我的 ComboBox 运行良好。
最佳答案
解决方案
我需要指定属性“Command”和“CommandParameter”的样式,如下所示:
<Menu Layout="Text" Margin="10,0,0,0">
<MenuItem Header="Group by" ItemsSource="{Binding GroupByOptions}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command"
Value="{Binding ViewModel.GroupCommand, RelativeSource={RelativeSource AncestorType={x:Type Views:MyView}}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
</Menu>
请注意,CommandParameter 是用户选择的实际“标题”。 (这就是我正在寻找的)我不知道,但是当你执行 {Binding} 时,它会获取实际的字符串。
在我的 ViewModel 中,它是这样的:
private ICommand mSortCommand;
//Implement get and set with NotifyPropertyChanged for mSortableList
private ICollectionView mSortableList;
public ICommand SortCommand
{
get { return mSortCommand ?? (mSortCommand = new RelayCommand(SortMyList)); }
}
public void SortMyList(object sortChosen)
{
string chosenSort = sortChosen as string;
CampaignSortableList.SortDescriptions.Clear();
Switch(chosenSort){
"Sort my List"
}
CampaignSortableList.Refresh();
}
现在一切正常。
关于c# - 如何在 WPF 中获取 "Selected MenuItem",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201773/