Search code examples
c#wpfuser-controlscontextmenumvvm-light

RelayCommand not firing from Context Menu item in a user control


In a user control I have context menu for data grid like shown below

<DataGrid.ContextMenu>
     <ContextMenu Focusable="False">
         <menuItems:ExportMenuItemView DataContext="{Binding ExportMenuItemVM}"/>
     </ContextMenu>
</DataGrid.ContextMenu>

in the view model class I have the view property

public ExportMenuItemViewModel ExportMenuItemVM {get;set;}

ExportMenuItemView is a user control which contains a menu item

<UserControl x:Class="MenuControl.View.ExportMenuItemView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="20" d:DesignWidth="200">
    <MenuItem Header="Export" Focusable="False" Command="{Binding Export}"/>
</UserControl>

Below is the view model class for the Export View

namespace MenuControl.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class ExportMenuItemViewModel : ViewModelBase
    {
        public ExportBlockMenuItemViewModel(IExport exporter)
        {
            Export = new RelayCommand(() => exporter.Export());
        }
        public RelayCommand Export { get; set; }
    }
}

RelayCommand Export is not getting executed when I click the menu item "Export". I am using MVVLLight


Solution

  • Found solution I need to create a separate function. If I call the operation as a lambda function as shown below, it is not working

    Export = new RelayCommand(() => exporter.Export());
    

    I need to create a function "foo" and give that in the relay command like shown below. I do know the reason but when I change the code as below, it started working

    Export = new RelayCommand(foo);
    private void foo()
    {
       exporter.Export()
    }