Thursday, October 18, 2007

How to build dynamic menus and toolbars

The challenge is as following:

  • I want to have external XAML files with menus and toolbars
  • I do not want to recompile 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

What's the problem? The answer is XamlReader. First let's create menus and toolbars in external loose XAML files and put them into our BIN directory.


<Menu xmlns=""
  <MenuItem Header="Edit">
    <MenuItem Command="ApplicationCommands.Cut"/>
    <MenuItem Command="ApplicationCommands.Copy"/>
    <MenuItem Command="ApplicationCommands.Paste"/>


<ToolBar xmlns=""
  <Button Command="ApplicationCommands.Cut">
    <Image Source="pack://siteoforigin:,,,/cut.png"/>
    <Button Command="ApplicationCommands.Copy">
      <Image Source="pack://siteoforigin:,,,/copy.png"/>
    <Button Command="ApplicationCommands.Paste">
      <Image Source="pack://siteoforigin:,,,/paste.png"/>


Now let's create out window


<Window x:Class="DynamicMenu.Window1"
    Title="DynamicMenu" Height="300" Width="300"
    <Style TargetType="Image">
        <Trigger Property="IsEnabled" Value="False">
          <Setter Property="Opacity" Value="0.5"/>
    <StackPanel Name="main">


Now, the only thing we should do it to read Menu1.xaml and TooBar1.xaml from our BIN directory and add Menu and ToolBar controls dynamically to the page

public Window1()
           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);



We done. Have a nice day :)

Source code for this article

No comments: