Search code examples
c#wpfmvvmmenu-items

Sub-MenuItem Selection in MVVM


I have the following XAML used to populate a sub-MenuItem listing with RecentDocuments:

<MenuItem Header="_Recent Studies" 
          ItemsSource="{Binding RecentFiles}"
          AlternationCount="{Binding Path=Items.Count, 
                                     Mode=OneWay, 
                                     RelativeSource={RelativeSource Self}}" 
          ItemContainerStyle="{StaticResource RecentMenuItem}"/>

Where in the ViewModel I have the following RecentFiles property

private ObservableCollection<RecentFile> recentFiles = new ObservableCollection<RecentFile>();
public ObservableCollection<RecentFile> RecentFiles
{
    get { return this.recentFiles; }
    set
    {
        if (this.recentFiles == value)
            return;
        this.recentFiles = value;
        OnPropertyChanged("RecentFiles");
    }
}       

Now this works fine and displays my recent menu items like so:

MenuItems

My question is; how can I bind to the click event on my recent files MenuItems? I am amble to use AttachedCommands but I don't see how this can be achieved.

thanks for your time.


Solution

  • If you are using MVVM pattern, you do not need Click event at all.

    You should use MenuItem.Command property in order to communicate with your ViewModel.

    HOW?

    As I can see, you are using the ItemContainerStyle. You can add the following line to that style:

    <Style x:Key="RecentMenuItem" TargetType="MenuItem">
        ...
        <Setter Property="Command" Value="{Binding Path=SelectCommand}" />
        ...
    </Style>
    

    And in your RecentFile:

     public ICommand SelectCommand { get; private set; }
    

    You can initialize the command inside the constructor of RecentFile class.