【问题标题】:How can I get the "Selected MenuItem" in WPF如何在 WPF 中获取“选定的菜单项”
【发布时间】:2013-04-18 13:57:30
【问题描述】:

我想知道如何从菜单中获取“选定”菜单项。 基本上,我想获得“选定的”MenuItem,这样我就可以对我的 ListBox 进行排序。 这是我的菜单 XAML。

<Menu>
    <MenuItem Header="Sort by" ItemsSource="{Binding SortByOptions}"
                            *SelectedItem="{Binding GroupBy}"*/>
</Menu>

我用菜单切换了我的组合框,但在菜单中,“SelectedItem”不像在组合框中那样存在。我想知道我怎样才能从菜单中获得选择的项目。

C#

ItemsSource 绑定“SortByOptions”是包含要排序的选项的字符串的 ObservableCollection。 绑定“GroupBy”是每次用户选择另一个菜单项时设置的字符串。

每次用户选择另一个菜单项时,我都在搜索设置变量“GroupBy”。

以前,我的 ComboBox 运行良好。

【问题讨论】:

  • MenuItem.Checked?您可以遍历菜单上的所有项目,并检查每个项目是否如此。如果是,则该项目已被选中。
  • 请修改您的问题,以阐明所选菜单项的含义。您是想将最近使用的命令放在顶部,还是其他?
  • 在我看来,菜单似乎不能很好地替代组合框。您能否提供更多详细信息,说明您要完成的工作以及原因..
  • @RogerN 我希望每次都能收到来自菜单中所有选项的用户选择通知。
  • @Niclas 我正在从 ComboBox 切换到 Menu,因为有人告诉我这样做。

标签: c# xaml wpf-controls


【解决方案1】:

解决方案

我需要像这样指定属性“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();
}

现在一切正常。

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2017-05-18
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多