How to load the WPF controls dynamically at Runtime

Posted By  Prabu On 04 Jul 2010 10:07:30
emailbookmarkadd commentsprint
No of Views:1562
Bookmarked:0 times
Votes:0 times

Introduction

In order to load the WPF controls dynamically at Runtime, 

Implementation

please do the following steps.

1. Create a dummy XAML content file (Dynamic_Content.xaml) with Controls details.

<StackPanelxmlns="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");
}

 That's all.i hope this is help to you.

Sign Up to vote for this article
Other popular Tips/Tricks
    Comments
    There is no comments for this articles.
    Leave a Reply
    Title:
    Display Name:
    Email:
    (not display in page for the security purphase)
    Website:
    Message:
    Please refresh your screen using Ctrl+F5
    If you can't read this number refresh your screen
    Please input the anti-spam code that you can read in the image.
    ^ Scroll to Top