我有一个带有一些数据的 ListView 和一个 ItemContainerStyle 来将 ContextMenu 绑定到每个项目(所以它只在点击时出现 ListView 中的项目 我已经在 ListView.Resources 中定义了 ContextMenu 。如何正确触发 ContextMenuOpening 事件,然后在所述事件中访问 ContextMenuEventArgs 中的 ContextMenu ?
ListView.Resources>
<ContextMenu x:Key="ItemContextMenu" FontFamily="Verdana" FontSize="14">
//Rest of the ContextMenu
<MenuItem Header="Custom Actions">
</MenuItem>
</ContextMenu>
</ListView.Resources>
现在,我试图在风格中设置事件设定器,
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource ItemContextMenu}" />
<EventSetter Event="ContextMenuOpening" Handler="ContextMenu_ContextMenuOpening" />
</ListView.ItemContainerStyle>
但是这会在C#-Code中触发 NullPointerException (基本上是从https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/how-to-handle-the-contextmenuopening-event复制的)
private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
FrameworkElement fe = e.Source as FrameworkElement;
ContextMenu cm = fe.ContextMenu;
List<MenuItem> customActions = new List<MenuItem>();
customActions.Add(new MenuItem {Header = "First Thing"});
customActions.Add(new MenuItem {Header = "Second Thing"});
foreach (MenuItem mi in cm.Items) // here is the NullPointerException
{
if((String)mi.Header == "Custom Actions")
{
foreach(MenuItem cmi in customActions)
{
mi.Items.Add(cmi);
}
}
}
}
如何在打开之前访问 ContextMenu 并修改它?