Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Instantiating a class written in XAML from code.

by Ioannis Panagopoulos

There are some times when you want to write a specific framgent of the UI in XAML and then intantiate it in a code-behind file. This can also lead to the strange situation of being able to change the UI design completely afer the application has been compiled and shipped.

Here is how such thing can be done:

Suppose that you have written the following XAML code:

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Orientation="Horizontal" Height="50">
<TextBox x:Name="TextBoxTest" Width="100" VerticalAlignment="Center" Margin="5 0 5 0"/>
<Button x:Name="ButtonTest" Content="Click Me" VerticalAlignment="Center"/>
</StackPanel>

This code displays the following:

  

Add a new TextFile to your project and name it "StackPanel.xaml". Write within the file the previous XAML code. Now set its "Build Action" to "Embedded Resource".

In the Window1.xaml write the following lines:

<Window x:Class="XAMLImportTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel x:Name="TestPanel">
</StackPanel>
</Window>
 

To load the StackPanel.xaml at runtime and display it in the GUI write the following in the Window's constructor (after InitializeComponent()): 

public Window1()
{
InitializeComponent();
System.IO.Stream StackPanelSpectsStream =
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("XAMLImportTests.StackPanel.xaml");
StackPanel ContainingItem = System.Windows.Markup.XamlReader.Load(StackPanelSpectsStream) as StackPanel;
 
this.TestPanel.Children.Add(ContainingItem);
}

Setting the StackPanel.xaml as Embedded Resource, effectively hides it within the executable. If you want it available for edit you can set its "Build Action" to "None" and its "Copy to Ouput Directory" to "Copy Always". Substitute the Window1 method's code to the following:

public Window1()
{
InitializeComponent();
 
System.Xml.XmlReader rdr = new System.Xml.XmlTextReader(@".\StackPanel.xaml");
StackPanel ContainingItem = System.Windows.Markup.XamlReader.Load(rdr) as StackPanel;
 
this.TestPanel.Children.Add(ContainingItem);
}
 

Now you can change the GUI after compilation by altering the StackPanel.xaml file. If you want to manipulate the file's controls (such as setting the Text property of the TextBox) you can navigate through the hierarchy of the controls (ContainingItem.Children[0]....):

TextBox Test = ContainingItem.Children[0] as TextBox;
Test.Text = "Hello";
 

kick it on DotNetKicks.com

Shout it

blog comments powered by Disqus
hire me