简体   繁体   中英

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. However, when I try to do this in C# it will not compile. I've checked several existing StackOverflow questions, but they seem to be using different controls or are for WinForms instead.

<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.

在此处输入图像描述

Can you try this?

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

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