Adding dynamic XAML using managed JavaScript
You can use managed JavaScript code to dynamically add XAML objects that are rendered to the browser in the Silverlight application. This is one of the most powerful features of the DLR because it allows you to employ the strengths of the scripting language to create a content-rich interface for the user.
One of the biggest strengths of the DLR is that almost every Silverlight object has a constructor. You can use that constructor rather than having to use CreateFromXaml() or a XamlReader to build XAML objects.
To create an XAML object in managed JavaScript, simply call the constructor function. For example, to create a Canvas and a TextBlock object, use the following managed JavaScript code:
After you create the object, you can modify its properties using standard dot syntax. For example, to set the size of a Canvas object, use the following managed JavaScript code:
As with .NET programming, you cannot use string values for properties such as the Source property of an Image control or the Margin property of a StackPanel control. To set those values, you need to use the appropriate object from the CLR library.
For example, the following managed JavaScript code creates a SolidColorBrush object to set the Foreground color of a TextBlock:
xaml.titleBlock.Foreground = new SolidColorBrush(Colors.Red)
At times you may still want to use an XAML reader to generate an XAML DOM from a well-formed XAML string. To do this you can use the Load function of an XamlReader object to generate the XAML from a string. For example, the following managed JavaScript code creates an XAML DOM with the root object being a Canvas:
myXaml = XamlReader.Load('.....<Canvas xmlns='http://schemas.microsoft.com/client/2 007' Width='2 00' Height='200' Background='Blue' Canvas.Top='%d' Canvas.Left='%d'>
<TextBlock Text='%s' Canvas.Top='10' Canvas.Left='15'
Text=MSomeTextM/>
The XAML text needs to be well formed and must include an xmnls property, typically xmlns=,http://schemas.microsoft.com/client/2007', for Silverlight to be able to generate the XAML DOM.
Post a comment