14.15. Loading XAML Dynamically

Silverlight allows you to load XAML at runtime. You might want to do this to reduce your application size, spread out loading through your application's lifetime, or dynamically load content. When you have retrieved your XAML content as a string, you need to pass it into the XamlReader.Load() method. All that is then necessary to do is cast the results of XamlReader.Load() to the type of object the XAML represents.

When constructing the XAML, be sure to add the xmlns namespace property to your objects; otherwise, Silverlight will be unable to determine the type of object you are trying to create. The following is a simple example illustrating loading a TextBlock from a string that would be placed in the code behind of a XAML file (and assumes an element called LayoutRoot exists):

string XAMLContent=@"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/
presentation""  Canvas.Left=""200"" Canvas.Top=""100"" Text=""Hello""></TextBlock>";

TextBlock TextBlock=(TextBlock) System.Windows.Markup.XamlReader.Load(XAMLContent);
LayoutRoot.Children.Add(TextBlock);

Unless you are creating just one XAML object, you probably want to load your XAML within a layout control such as Canvas. You can then easily cast the result of the Load() method to a Canvas object.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.41.235