c# - 如何处理 WPF 数据绑定(bind)菜单中的单击事件

标签 c# wpf data-binding

我有一个 MenuItem,其 ItemsSource 数据绑定(bind)到一个简单的字符串列表,它显示正确,但我正在努力了解如何为它们处理点击事件!

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

<Window x:Class="WPFDataBoundMenu.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <Menu>
        <MenuItem Header="File" Click="MenuItem_Click" />
        <MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" />
    </Menu>
</Grid>

using System.Collections.Generic;
using System.Windows;

namespace WPFDataBoundMenu
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public List<string> MyMenuItems { get; set;}

        public Window1()
        {
            InitializeComponent();
            MyMenuItems = new List<string> { "Item 1", "Item 2", "Item 3" };
            DataContext = this;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("how do i handle the other clicks?!");
        }
    }
}

非常感谢!

克里斯。

最佳答案

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

代码隐藏..

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

事件将冒泡到公共(public)处理程序。然后,您可以使用 Header 文本或更好的 DataContext 属性来根据需要进行切换和操作

关于c# - 如何处理 WPF 数据绑定(bind)菜单中的单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/330444/

相关文章:

c# - 为什么 KeyDown 事件无法访问绑定(bind)变量的当前值?

c# - 限制 ListView 中的列大于 X(NotifyPropertyChanged 不起作用)

.net - 我可以查看 Visibility = Collapsed 的 WPF ComboBoxItem。这是WPF错误吗?

wpf - 滚动和拉伸(stretch)扩展器的内容

c# - 安全通信 PHP (phpseclib) 和 C# (Unity 3D)

javascript - knockoutjs 中的选项、optionsText 和 optionsValue

angularjs - 如何在 AngularJs 中将对象绑定(bind)到 dom 元素

c# - .Net 3.5 到 4 的迁移导致应用程序变慢

c# - 如何在 asp.net 中发回 JSON?

c# - 禁用页面元素和显示 UpdateProgress 控件的模拟