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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With