Windows VistaVisual Studio 2008XAML.NET 3.0Visual Studio 2005Windows XP.NET 3.5初学者C# 3.0WPF开发Visual StudioWindows.NETC#
如何在 WPF 中构建动态菜单和工具栏?






3.56/5 (8投票s)
本文档解释了如何使用 WPF 内置功能将菜单、工具栏或任何其他内容动态地插入到您的应用程序中。
引言
WPF 是一种非常动态的语言。它包含非常智能的对象,使您能够动态地加载、解析和显示内容。更重要的是,您甚至可以创建自定义事件处理程序(命令)并将它们绑定到松散的 XAML 文件中,这些文件将在运行时加载,只要您需要,而无需重新编译应用程序代码。
背景
挑战如下:
- 我希望拥有包含菜单和工具栏的外部 XAML 文件。
- 如果我想更改这些菜单和工具栏中的内容,我不想重新编译项目。
- 我希望为这些菜单和工具栏提供命令,而无需重新编译。
- 我希望编写最少的代码来提供此功能。

Using the Code
让我们在 Menu.xaml 文件中创建我们的菜单。这是一个松散的 XAML 文件,不包含 C# 代码。
<Menu xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<MenuItem Header="Edit">
<MenuItem Command="ApplicationCommands.Cut"/>
<MenuItem Command="ApplicationCommands.Copy"/>
<MenuItem Command="ApplicationCommands.Paste"/>
</MenuItem>
</Menu>
我将所有将在应用程序中使用的内容都放入此文件中。在这种情况下,这些是三个常用的剪贴板命令:剪切、复制和粘贴。ApplicationCommand
将处理这些命令并为我提供所需的功能。
现在,让我们在 ToolBar1.xaml 文件中创建一个工具栏。
<ToolBar xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button Command="ApplicationCommands.Cut">
<Image Source="pack://siteoforigin:,,,/cut.png"/>
</Button>
<Button Command="ApplicationCommands.Copy">
<Image Source="pack://siteoforigin:,,,/copy.png"/>
</Button>
<Button Command="ApplicationCommands.Paste">
<Image Source="pack://siteoforigin:,,,/paste.png"/>
</Button>
</ToolBar>
最后但并非最不重要,为我的主 Window
编写 XAML 代码,名为 Window1.xaml。在这里,我将放置自定义样式,以确保一旦任何 Image
或其父控件被禁用,图像将变为半透明。
<Window x:Class="DynamicMenu.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DynamicMenu" Height="300" Width="300"
>
<Window.Resources>
<Style TargetType="Image">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.5"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Name="main">
<TextBox/>
<TextBox/>
</StackPanel>
</Window>
现在,当我们拥有所有 XAML 文件后,我们必须加载我的动态菜单和工具栏,并将其添加到应用程序中。为了执行此操作,我们将使用 XamlReader
,它将读取和解析我的松散 XAML 并将其添加到应用程序中。
public Window1()
{
InitializeComponent();
using (FileStream s = new FileStream("Menu1.xaml", FileMode.Open))
{
Menu menu = XamlReader.Load(s, new ParserContext()) as Menu;
if (menu != null)
{
main.Children.Insert(0, menu);
}
}
using (FileStream s = new FileStream("ToolBar1.xaml", FileMode.Open))
{
ToolBar tool = XamlReader.Load(s, new ParserContext()) as ToolBar;
if (tool != null)
{
main.Children.Insert(1, tool);
}
}
}
关注点
为了实现如此丰富的功能,您无需重新编译任何内容,这真是太好了!
历史
- 2007 年 11 月 1 日:初始发布