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

Chr*_*wne 10 c# data-binding wpf

我有一个MenuItem,其中ItemsSource被数据绑定到一个简单的字符串列表,它显示正确,但我很难看到我如何处理它们的点击事件!

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

<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>
Run Code Online (Sandbox Code Playgroud)

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?!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢!

克里斯.

Gis*_*shu 14

<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" Click="DataBoundMenuItem_Click" />
Run Code Online (Sandbox Code Playgroud)

代码背后..

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

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


Ken*_*art 5

您可以使每个菜单项执行相同的命令,从而集中处理执行。如果您需要区分实际对象实例之外的菜单项,那么也可以绑定command参数:

<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Command" Value="{x:Static local:MyCommands.MyCommand}"/>
            <Setter Property="CommandParameter" Value="{Binding SomeProperty}"/>
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>
Run Code Online (Sandbox Code Playgroud)

SomeProperty假定是MyMenuItems集合中每个项目的属性。因此,您的命令执行处理程序将收到所SomeProperty单击的特定菜单项的值。