Wednesday, November 20, 2013

Dynamically Loading XAML in WPF

Dynamically Loading XAML in WPF

Loading XAML at run time is really simple. I wrote a small sample to load the XAML at run time and than attach the event handler with the XAML object. I created following XAML page and copied it to the debug folder.
<Page 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1">
    <Grid>
        <Button Margin="0,0,9,38" Name="button1" Height="82" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="132">Button</Button>
    </Grid>
</Page>
and here is the C# code
public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            LoadXAMLMethod(); 
        }

        Button ButtoninXAML;
        public void LoadXAMLMethod()
        {
            try
            {
                StreamReader mysr = new StreamReader("Page1.xaml");
                DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
                ButtoninXAML = LogicalTreeHelper.FindLogicalNode(rootObject, "button1") as Button ; 
                ButtoninXAML.Click += new RoutedEventHandler(Button_Click); 
                this.Content = rootObject;
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message.ToString());    
            }
        }
        public void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hi WPF");  
        }
    }
}
do not forget to add following namespaces.

using System.IO;
using System.Windows.Markup;

Reference:
http://blogs.msdn.com/b/ashish/archive/2007/08/14/dynamically-loading-xaml.aspx

No comments: