WPF之Menu绑定XML

时间:2021-09-29 15:30:19

一、XML文件

<?xml version="1.0" encoding="utf-8" ?>
<MenuData xmlns="">
  <Operation  Name="文件" Gesture="F">
    <Operation Name="新建" Gesture="N">
      <Operation Name="网站" Gesture="Control+W">
      </Operation>
      <Operation Name="文档" Gesture="Control+D">
      </Operation>
      <Operation Name="项目" Gesture="Control+P">
      </Operation>
    </Operation>
  </Operation>
  <Operation  Name="编辑" Gesture="E">
    <Operation Name="复制" Gesture="Control+C">
    </Operation>
    <Operation Name="粘贴" Gesture="Control+V">
    </Operation>
  </Operation>
  <Operation  Name="帮助" Gesture="E">  
  </Operation>
</MenuData>

二、Xaml文件

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <XmlDataProvider x:Key="menudata" Source="MenuData.xml" XPath="MenuData/Operation"></XmlDataProvider>
        <HierarchicalDataTemplate DataType="Operation"
                                  ItemsSource="{Binding XPath=Operation}">
            <StackPanel Orientation="Horizontal" >
                <TextBlock Text="{Binding XPath=@Name}" HorizontalAlignment="Left"></TextBlock>
                <TextBlock Text="{Binding XPath=@Gesture}" HorizontalAlignment="Left"></TextBlock>
            </StackPanel>
            
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <StackPanel MenuItem.Click="StackPanel_Click">
           
                <Menu ItemsSource="{Binding Source={StaticResource menudata}}"></Menu>
            
        </StackPanel>
           
      
    </Grid>
</Window>

三、后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

    

        private void StackPanel_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.OriginalSource as MenuItem;
            XmlElement xe = mi.Header as XmlElement;
            MessageBox.Show(xe.Attributes["Name"].Value);
        }
    }
}