Dan*_*scu 5 c# xaml wpf-controls
我想知道如何从菜单中获取“选定的”菜单项。基本上,我想获得“选定的”菜单项,以便我可以对列表框进行排序。这是我的菜单 XAML。
<Menu>
<MenuItem Header="Sort by" ItemsSource="{Binding SortByOptions}"
*SelectedItem="{Binding GroupBy}"*/>
</Menu>
Run Code Online (Sandbox Code Playgroud)
我用菜单切换了我的 ComboBox,但在菜单中,“SelectedItem”不像在 ComboBox 中那样存在。我想知道如何从菜单中选择什么项目。
C#
ItemsSource 绑定“SortByOptions”是包含排序选项的字符串的 ObservableCollection。绑定“GroupBy”是一个字符串,每次用户选择另一个 MenuItem 时都会设置该字符串。
每次用户选择另一个 MenuItem 时,我都在搜索设置变量“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>
Run Code Online (Sandbox Code Playgroud)
请注意,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();
}
Run Code Online (Sandbox Code Playgroud)
现在一切正常。