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
CodePudding user response:
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
CodePudding user response:
In your app.xaml add the following resource:
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type local:ExportMenuItemViewModel}">
<local:ExportMenuItemView />
</DataTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>