Hi,@zequion.Welcome to Microsoft Q&A. To dynamically add event handlers to items in a context menu in WPF and pass index parameters to these handlers, you could refer to the following sample code, which creates a context menu, adds items to it, and assigns event handlers with the correct index passed dynamically.
<Grid >
<Button x:Name="Form_Estilos" Content="Styles Button" Width="200" Height="50">
<Button.ContextMenu>
<ContextMenu x:Name="Form_Estilos_Items"/>
</Button.ContextMenu>
</Button>
</Grid>
In the C# code-behind, you'll programmatically add MenuItems to the ContextMenu, then loop through those items to attach event handlers for Click and MouseEnter, passing the index to the event handler .
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddMenuItemsToContextMenu();
}
private void AddMenuItemsToContextMenu()
{
Form_Estilos_Items.Items.Clear();
for (int i = 0; i < 5; i++)
{
MenuItem menuItem = new MenuItem();
menuItem.Header = $"Style {i + 1}";
int index = i;
menuItem.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler((sender, e) => Fcn_Menu_Estilo_ButtonItem_Apoyo(sender, e, index)));
menuItem.AddHandler(MenuItem.MouseEnterEvent, new RoutedEventHandler((sender, e) => Fcn_Menu_Estilo_ButtonItem_Apoyo(sender, e, index + 1)));
Form_Estilos_Items.Items.Add(menuItem);
}
}
public static void Fcn_Menu_Estilo_ButtonItem_Apoyo(object sender, RoutedEventArgs e, int index)
{
MessageBox.Show($"Event fired for Style {index }", "Event Handler", MessageBoxButton.OK, MessageBoxImage.Information);
}
You can customize how index is calculated or passed to the handler. Replace the MessageBox.Show with your actual event handling logic.
If the problem persists, you could share more complete sample code that reproduces the issue.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.