I'm trying to convert a string list to ContexMenu
. How do I apply click events to each item and display a message with the text of the clicked item?
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>
Image
CodePudding user response:
You can do this in 2 ways.
Through building ContextMenu
from code-behind:
// ----- 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;
Through setting click handlers from XAML for each 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");
}