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.

XAML

This is an example of my Xaml

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF45"
    xmlns:ViewModel="clr-namespace:[yournamespace].ViewModel" x:Class="[yourassembly]"
    Height="350" Width="525">
    <StackPanel>
        <Menu Height="20">        
            <MenuItem Header="_AMenuItem">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <cmd:EventToCommand Command="{Binding Main.MenuCommand, Mode=OneWay}" CommandParameterValue="AnArgument"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <MenuItem.DataContext>
                    <ViewModel:ViewModelLocator/>
                </MenuItem.DataContext>
            </MenuItem>
        </Menu> 
    </StackPanel>
</Window>

ViewModel

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.
        ////}
        ////else
        ////{
        ////    // 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; }
}

Conclusion

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