DataGrid上下文菜单事件未触发

时间:2014-08-25 15:21:42

标签: c# wpf mvvm

这就是我所拥有的:

<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;
        }
}

问题是永远不会达到MainGridContextMenuItemChange方法。这可能与上下文菜单没有看到LogsViewModel DataContext有关吗?我该如何勾选?感谢。

1 个答案:

答案 0 :(得分:0)

试试这个

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

ContextMenu不是LogicalTree的一部分,因此它不能从Parent继承DataContext。但是ContextMenu确实有Property PlacementTarget,我们可以使用它来使用绑定获取DataGrid的DataContext,如上所示。

  

设置ContextMenu的DataContext的第二个选项是

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