WPF之Menu綁定XML

1、XML文件ide

<?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>

2、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>

3、後臺代碼spa

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);
        }
    }
}
相關文章
相關標籤/搜索