I've got a viewmodel that contains a collection of objects and a bunch of commands.
public class MainWindowVM : NotifyPropertyChangedBase
{
private CollectionViewSource employeeViewSource;
private ICommand cmdOpenDetailEmployee;
public MainWindowVM()
{
nsDataProviderEmployees = new NSDataProvider();
employeeViewSource = new CollectionViewSource();
cmdOpenDetailEmployee = new RelayCommand<object>((parameter) => {...});
this.LoadData();
}
public CollectionViewSource EmployeeViewSource => employeeViewSource;
public ICommand CmdOpenDetailEmployee => cmdOpenDetailEmployee;
}
In my application I want to use this command in a context menu of the datagrid showing the employees.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyApp.UI"
xmlns:DataModel="clr-namespace:MyApp.DataModel;assembly=MyApp.DataModel" x:Class="MyApp.UI.MainWindow"
xmlns:vm="clr-namespace:MyApp.UI.ViewModels"
mc:Ignorable="d"
Title="MyApp - Main" Height="751.826" Width="1111.005" Loaded="Window_Loaded" Icon="Resources/MyApp.ico">
<Window.DataContext>
<vm:MainWindowVM />
</Window.DataContext>
<Grid x:Name="grdMain">
<DataGrid DataContext="{Binding Path=EmployeeViewSource}" x:Name="employeeDataGrid" EnableRowVirtualization="True" ItemsSource="{Binding}" Margin="10,77,10,0" RowDetailsVisibilityMode="VisibleWhenSelected">
<DataGrid.ContextMenu>
<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">
<MenuItem Header="OpenDetail..."
Command="{Binding CmdOpenDetailEmployee}"
CommandParameter="{Binding}"/>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>...</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
The Problem is I am unable to come up with a combination of bindings that both let me use the EmployeeViewSource
property or my ViewModel as DataContext for the grid AND the CmdOpenDetailEmployee
property of my ViewModel as the DataContext for my ContextMenu and MenuItems.
According to all the posts I've been able to find this should work but the command isn't executed when I click the menu item.