首页 > 代码库 > WPF之Menu绑定XML
WPF之Menu绑定XML
一、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); } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。