简体   繁体   中英

DataGrid Context Menu Event Not Firing

This is what I have:

<window>
<Window.Resources>        
    <DataTemplate DataType="{x:Type viewModel:LogsViewModel}" >
                            <DataGrid Name="MainLogDataGrid" ItemsSource="{Binding MainLogDataGrid}">

<DataGrid.ContextMenu>
<ContextMenu Name="MainGridContextMenu" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp" >
<i:InvokeCommandAction Command="{Binding OnMainDataGridContextMenuChange}" 
                 CommandParameter="{Binding ElementName=MainGridContextMenu, Path=PlacementTarget}" /> 
</i:EventTrigger>
</i:Interaction.Triggers>
<MenuItem Header="Insert Row" Name="InsertRowMenuItem" TabIndex="0" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>

<DataTemplate DataType="{x:Type viewModel:ReportsViewModel}">
    <Label FontSize="50">THIS IS WHERE THE REPORTS GO</Label>
</DataTemplate>
</Window.Resources>
</Window>
<ContentControl  Content="{Binding CurrentPageViewModel}" />


    class LogsViewModel : ObservableObject, IViewModel
    {
        public RelayCommand<object> OnMainDataGridContextMenuChange { get; private set; }

        public LogsViewModel()
        {
            OnMainDataGridContextMenuChange = new RelayCommand<object>(MainGridContextMenuItemChange);

        }

        private void MainGridContextMenuItemChange(object menuItem)
        {
            var item = menuItem as MenuItem;
        }
}

The problem is that MainGridContextMenuItemChange method is never reached. Could this have something to do with the context menu not seeing LogsViewModel DataContext? How can I hook tihs up? Thanks.

Try this

 <ContextMenu Name="MainGridContextMenu"  DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">

ContextMenu is not a part of LogicalTree so it cannot inherit the DataContext from Parent .However ContextMenu do have Property PlacementTarget and we can use it to get the DataContext of DataGrid using binding as shown above.

Second option to set the DataContext of ContextMenu is

 <ContextMenu Name="MainGridContextMenu" DataContext="{Binding DataContext, Source={x:Reference MainLogDataGrid}}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM