|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionWPF 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. BackgroundThe challenge is as follows:
Using the CodeLet's create our menu in the Menu.xaml file. This is a loose XAML file and it does not contain C# code behind. <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>
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. Now, let's create a toolbar in the ToolBar1.xaml file. <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>
And last but not least, XAML code for my main <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>
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 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);
}
}
}
Points of InterestIsn't it nice that you have not recompiled anything in order to achieve very rich functionality? History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||