MVVMLight MenuItem Click EventToCommand Example

MVVMLight MenuItem Click EventToCommand Example

18 August 2013

I'm new to Windows WPF and I wanted to transfer my knowledge of Knockoutjs MVVM to my first WPF project.

I decided to use MVVMLight based on my first impression being that it looks as though it still has community activity!

Binding the MenuItem Click event to the ViewModel

In my scenario I wanted to bind the Click event of a MenuItem to a command on the ViewModel.


This is an example of my Xaml

    xmlns:ViewModel="clr-namespace:[yournamespace].ViewModel" x:Class="[yourassembly]"
    Height="350" Width="525">
        <Menu Height="20">        
            <MenuItem Header="_AMenuItem">
                    <i:EventTrigger EventName="Click">
                        <cmd:EventToCommand Command="{Binding Main.MenuCommand, Mode=OneWay}" CommandParameterValue="AnArgument"/>


Below is a portion of my ViewModel

public class MainViewModel : ViewModelBase
    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel()
        ////if (IsInDesignMode)
        ////    // Code runs in Blend --> create design time data.
        ////    // Code runs "for real"

        MenuCommand = new RelayCommand<string>((o) => {
            //DO STUFF HERE!!!!


    /// <summary>
    /// A command raised as a consequence of clicking a menu
    /// </summary>
    public RelayCommand<string> MenuCommand { get; set; }


The gist of what's happening is we're asking MVVMLight to observe the Click event on the MenuItem and adapt it to a command using EventToCommand registering the command handler called MenuCommand passing in an argument AnArgument.

.NET MVVM Patterns