简体   繁体   English

在 WPF 中使用单击处理程序动态添加上下文菜单项

[英]Dynamically Adding a Context Menu Item with a Click Handler in WPF

I have a list view with a context menu.我有一个带有上下文菜单的列表视图。 I am looking to dynamically add an item which has a click event.我正在寻找动态添加具有点击事件的项目。 As you can see below, doing it statically is pretty straight forward in the XAML.正如您在下面看到的,在 XAML 中静态执行此操作非常简单。 However, when I try to do this in C# it will not compile.但是,当我尝试在 C# 中执行此操作时,它将无法编译。 I've checked several existing StackOverflow questions, but they seem to be using different controls or are for WinForms instead.我检查了几个现有的 StackOverflow 问题,但它们似乎使用不同的控件或用于 WinForms。

<ListView x:Name="listView" Margin="10,7,10,8">
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem x:Name="Test" Header="Test" Click="Test"/>
        </ContextMenu>
    </ListView.ContextMenu>
<ListView.View>

ModuleName is the name and DisplayModule() is the click handler event I want. ModuleName 是名称,而 DisplayModule() 是我想要的点击处理程序事件。

在此处输入图像描述

Can you try this?你能试试这个吗?

var menuItem = new MenuItem();
menuItem.Name = ModuleName;
menuItem.Header = null;
menuItem.Click += DisplayModule;
listView.ContextMenu.Items.Add(menuItem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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