如何使用列表在每个上下文菜单项上添加点击事件?
Posted
技术标签:
【中文标题】如何使用列表在每个上下文菜单项上添加点击事件?【英文标题】:How to add click event on each ContexMenu item using list? 【发布时间】:2021-12-26 19:02:18 【问题描述】:我正在尝试将字符串列表转换为ContexMenu
。如何将点击事件应用于每个项目并显示带有被点击项目文本的消息?
CS
public partial class MainWindow : Window
public MainWindow()
InitializeComponent();
List<string> list = new List<string>()
"item1", "item2", "item3"
;
context.ItemsSource = list;
XAML
<Window x:Class="wpftest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpftest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Name="grid" Background="Gray">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.ContextMenu>
<ContextMenu Name="context"/>
</Grid.ContextMenu>
</Grid>
</Window>
图片
【问题讨论】:
【参考方案1】:您可以通过两种方式做到这一点。
通过代码隐藏构建ContextMenu
:
// ----- XAML part
<Grid Name="grid" Background="Gray">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
</Grid>
// ----- Code part
// Initialize context menu
var contextMenu = new ContextMenu();
// Fill context menu with items
for (int i = 1; i <= 3; i++)
// Create simple item with some text on it
var menuItem = new MenuItem Header = "Item #" + i ;
// Add click handler
menuItem.Click += delegate _ = MessageBox.Show(menuItem.Header + " was clicked"); ;
// Add item to menu
contextMenu.Items.Add(menuItem);
// Set context menu to grid
grid.ContextMenu = contextMenu;
通过从 XAML 为每个 MenuItem
设置点击处理程序:
// ----- XAML part
<Grid Name="grid" Background="Gray">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Item #1" Click="ContextMenuItem_Click"/>
<MenuItem Header="Item #2" Click="ContextMenuItem_Click"/>
<MenuItem Header="Item #3" Click="ContextMenuItem_Click"/>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
// ----- Code part
// One click handler for each MenuItem.
// You can differ MenuItems by Header property for example
private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
if (sender is MenuItem menuItem)
_ = MessageBox.Show(menuItem.Header + " was clicked");
【讨论】:
以上是关于如何使用列表在每个上下文菜单项上添加点击事件?的主要内容,如果未能解决你的问题,请参考以下文章