DataGrid上下文菜单事件未触发
本文关键字:事件 上下文 菜单 DataGrid | 更新日期: 2023-09-27 18:19:24
我有:
<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有关吗?我怎样才能把这个连接起来?谢谢。
试试这个
<ContextMenu Name="MainGridContextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">
ContextMenu不是LogicalTree的一部分,所以它不能从Parent继承DataContext .然而,ContextMenu确实有PlacementTarget属性,我们可以使用它来获取DataGrid的DataContext,使用如上所示的绑定。
设置ContextMenu的DataContext的第二个选项是
<ContextMenu Name="MainGridContextMenu" DataContext="{Binding DataContext, Source={x:Reference MainLogDataGrid}}">