Tuesday, November 3, 2009

How to load the WPF controls dynamically at Runtime

In order to load the WPF controls dynamically at Runtime,  please do the following steps.

1. Create a dummy XAML content file (Dynamic_Content.xaml) with Controls details.
<StackPanel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">


    <Button x:Name="buttonStart" IsEnabled="True" Content="Start" Height="25" Width="100" Margin="5" />
    <Button x:Name="buttonStop" IsEnabled="False" Content="Stop" Height="25" Width="100" Margin="5" />


</StackPanel>

2. Select the file (Dynamic_Content.xaml) in Solution Explorer and  go to the properties.

3. Set “Build Action” as “Content” and “Copy to Output Directory” as “Copy always”.

4. Then you can use XamlReader class for reading the XAML content which we have the controls.

5. Please use the following code to read and load controls from XAML content file.



private void tab_TabItemAdded(object sender, TabItemEventArgs e)
{
    FileStream stream = new FileStream(@"Dynamic_Content.xaml", FileMode.Open, FileAccess.Read);
    StackPanel panel = XamlReader.Load(stream) as StackPanel;

    e.TabItem.Content = panel;
    e.TabItem.Header = string.Format("Tab Item - {0}", tab.Items.Count);
    stream.Close();

    Button buttonStart = panel.Children[0] as Button;
    buttonStart.Click += new RoutedEventHandler buttonStart_Click);           
}


void buttonStart_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Start button invloked");
}
Post a Comment