Tuesday, October 20, 2009

Dynamically load a xaml in WPF

i was looking for a way to load the xaml file on the fly.This will help the user to change the text color etc without building the application again.However Please note that loading XAML dynamically is not as efficient as compiling it. However, sometimes, it is necessary to load it dynamically at runtime.

Here i have a window - with 2 radiobutton.. checking will load respective pages.

here is the C# part
public partial class Window1 : Window
{
Button buttoninXAML;
public Window1()
{
InitializeComponent();

}

private void radioButton1_Checked(object sender, RoutedEventArgs e)
{
try
{
StreamReader mysr = new StreamReader(@"C:\test1.xaml");
DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
buttoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, "button1") as Button;
buttoninXAML.Click += new RoutedEventHandler(Button_Click);
myContainerframe.Content = rootObject;
}
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void radioButton2_Checked(object sender, RoutedEventArgs e)
{
try
{
StreamReader mysr = new StreamReader(@"C:\test.xaml");
DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
buttoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, "btntest") as Button;
buttoninXAML.Click += new RoutedEventHandler(Button_Click);
myContainerframe.Content = rootObject;
}
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

public void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Click of dynamically loaded btn");
}
}

Here is the xaml part of window

<stackpanel height="39" margin="12,12,12,0" name="stackPanel1" verticalalignment="Top" >
<radiobutton height="20" name="radioButton1" width="86" checked="radioButton1_Checked">SimplePage</radiobutton>
<radiobutton height="19" name="radioButton2" width="87" checked="radioButton2_Checked">Complexpage</radiobutton>
</stackpanel>


Regards
Balu

No comments:

Post a Comment