Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the "Selected MenuItem" in WPF

I was wondering how can I get the "Selected" MenuItem from a Menu. Basically, I want to get the "Selected" MenuItem so I can sort my ListBox. Here is my XAML for the Menu.

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

I Switched my ComboBox with a Menu, but in Menu, "SelectedItem" does not exist like in ComboBox. I was wondering how could I get what Item from menu was chosen.

C#

The ItemsSource Binding "SortByOptions" is an ObservableCollection of string who contains the options to sort. The binding "GroupBy" is a String that is set each time the user chose another MenuItem.

I am searching to set the variable "GroupBy" every time the user chose another MenuItem.

Before, my ComboBox worked well.

like image 672
Daniel Enachescu Avatar asked Apr 24 '13 20:04

Daniel Enachescu


1 Answers

SOLUTION

I needed to specify the style of the property "Command" and "CommandParameter" like this:

<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>

Note that the CommandParameter is the actual "Header" chosen by the user. (This is what I was searching for) I did not know, but when you do {Binding} it takes the actual string.

And in my ViewModel, here is what it looks like:

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();
}

It works all fine now.

like image 123
Daniel Enachescu Avatar answered Nov 15 '22 16:11

Daniel Enachescu