WPF is a very dynamic language. It contains very smart objects, enables you to load, parse and display content dynamically. More than this, you can even create custom event handlers (commands) and bind them into loose XAML files that will be loaded in runtime, whenever you need it without recompiling application code.
The challenge is as follows:
- I want to have external XAML files with menus and toolbars
- I do not want to recompile a project if I want to change something in those menus and toolbars
- I want to provide commands for those menus and toolbars without recompiling
- I want to write least amount of code to provide such functionality
Using the Code
Let's create our menu in the Menu.xaml file. This is a loose XAML file and it does not contain C# code behind.
I put into this file everything I'll use in the application. In this case, those are three common clipboard commands: Cut, Copy and Paste.
ApplicationCommand will take care of those commands and provide me with requested functionality.
Now, let's create a toolbar in the ToolBar1.xaml file.
And last but not least, XAML code for my main
Window, named Window1.xaml. Here, I'll put custom style to assure that once any of the
Images or its parent controls become disabled, the images become semi-transparent.
Title="DynamicMenu" Height="300" Width="300"
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.5"/>
Now, when we have all XAMLs, we have to load my dynamic menu and toolbar and add this into the application. To perform this action, we'll use
XamlReader that will read and parse my loose XAML and add it into the application.
using (FileStream s = new FileStream("Menu1.xaml", FileMode.Open))
Menu menu = XamlReader.Load(s, new ParserContext()) as Menu;
if (menu != null)
using (FileStream s = new FileStream("ToolBar1.xaml", FileMode.Open))
ToolBar tool = XamlReader.Load(s, new ParserContext()) as ToolBar;
if (tool != null)
Points of Interest
Isn't it nice that you have not recompiled anything in order to achieve very rich functionality?
- 1st November, 2007: Initial post