c# – 如何在WPF中的数据绑定菜单中处理点击事件

前端之家收集整理的这篇文章主要介绍了c# – 如何在WPF中的数据绑定菜单中处理点击事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个MenuItem,ItemsSource是数据绑定到一个简单的字符串列表,它正确显示,但我很难看到我如何处理他们的点击事件!

这是一个简单的应用程序,演示它:

  1. <Window x:Class="WPFDataBoundMenu.Window1"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="Window1" Height="300" Width="300">
  5. <Grid>
  6. <Menu>
  7. <MenuItem Header="File" Click="MenuItem_Click" />
  8. <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" />
  9. </Menu>
  10. </Grid>
  1. using System.Collections.Generic;
  2. using System.Windows;
  3.  
  4. namespace WPFDataBoundMenu
  5. {
  6. /// <summary>
  7. /// Interaction logic for Window1.xaml
  8. /// </summary>
  9. public partial class Window1 : Window
  10. {
  11. public List<string> MyMenuItems { get; set;}
  12.  
  13. public Window1()
  14. {
  15. InitializeComponent();
  16. MyMenuItems = new List<string> { "Item 1","Item 2","Item 3" };
  17. DataContext = this;
  18. }
  19.  
  20. private void MenuItem_Click(object sender,RoutedEventArgs e)
  21. {
  22. MessageBox.Show("how do i handle the other clicks?!");
  23. }
  24. }
  25. }

非常感谢!

克里斯.

解决方法

  1. <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" Click="DataBoundMenuItem_Click" />

代码背后..

  1. private void DataBoundMenuItem_Click(object sender,RoutedEventArgs e)
  2. {
  3. MenuItem obMenuItem = e.OriginalSource as MenuItem;
  4. MessageBox.Show( String.Format("{0} just said Hi!",obMenuItem.Header));
  5. }

事件会冒泡到普通的处理程序.然后,您可以使用头文本或更好的DataContext属性进行切换并根据需要进行操作

猜你在找的C#相关文章