0

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

  • Where do you initialize `ExportMenuItemVM` ? – Eduards Jun 24 '22 at 14:43
  • ExportMenuItemVM is initialized in the constructor of the view model class of the view containing. Like this DataGrid ExportMenuItemVM = new ExportMenuItemViewModel(exporterObject); – Anoopchandra Jun 24 '22 at 14:46

2 Answers2

0

I think you are missing something related to the DataContext Binding in your xaml like :

<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"
DataContext="{Binding Main, Source={StaticResource Locator}}">
    <MenuItem Header="Export" Focusable="False" Command="{Binding Export}"/>
</UserControl>

ViewModels in ViewModelLocator MVVM Light

pix
  • 1,264
  • 19
  • 32
0

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()
}