Silverlight学习笔记(二)-----XamlReader 动态加载SilverLight 对象

  通常情况下,Silverlight的界面元素都是通过直接读取XAML文件的内容来呈现的,但是在某些时候你并不能预先设计好所有的XAML元素,而是需要在程序运行的过程中动态地加载XAML对象,即是,如果希望一个XAML界面中的元素是由用户实时交互产生的,那么可以使用XamlReader.Load方法来实现。

【Sample】

XAML:

 1 <UserControl x:Class="XV.MainPage"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6 mc:Ignorable="d"
7 d:DesignHeight="300" d:DesignWidth="400">
8
9 <Canvas x:Name="parentCanvas" Background="White">
10
11 </Canvas>
12 </UserControl>

 

C#:

 1 namespace XV
2 {
3 public partial class MainPage : UserControl
4 {
5 public MainPage()
6 {
7 InitializeComponent();
8 StringBuilder xaml = new StringBuilder();
9 xaml.Append("<TextBlock ");
10 xaml.Append(
11 "xmlns=\"http://schemas.microsoft.com/client/2007\" ");
12 xaml.Append(
13 "Canvas.Left=\"50\" Canvas.Top=\"30\" FontSize=\"50\" ");
14 xaml.Append(
15 "FontWeight=\"Bold\" Text=\"动态创建XAML对象\"/>");
16 //创建 TextBlock 对象
17 TextBlock textBlock = (TextBlock)XamlReader.Load(xaml.ToString());
18 //添加TextBlock到parentCanvas
19 parentCanvas.Children.Add(textBlock);
20
21 //创建画笔的xaml对象
22 xaml = new StringBuilder();
23 xaml.Append("<LinearGradientBrush ");
24 xaml.Append(
25 "xmlns=\"http://schemas.microsoft.com/client/2007\" ");
26 xaml.Append(" StartPoint=\"0,0.5\" EndPoint=\"1,0.5\">");
27 xaml.Append("<GradientStop Color=\"White\" Offset=\"0.0\" />");
28 xaml.Append("<GradientStop Color=\"Green\" Offset=\"1.0\" />");
29 xaml.Append("</LinearGradientBrush> ");
30 //创建brush对象
31 LinearGradientBrush brush = (LinearGradientBrush)XamlReader.Load(xaml.ToString());
32 //应用画刷改变文本颜色
33 textBlock.Foreground = brush;
34 }
35 }
36 }

 

效果图:




  XAML中,UserControl下只包含了一个Canvas元素,而运行结果中产生的文字是通过XamlReader.Load的方法在C#中动态加载产生的。

【注意事项】

1、被XamlReader.Load加载的单个XAML内容必须包含XAML的命名空间,常用http://schemas.microsoft.com/client/2007

2、XAML文件中必须存在Silverlight根元素的内容,不能够使用XamlReader.Load替代整个XAML树。

3、使用XamlReader.Load创建的内容只能赋予一个Silverlight对象,他们是一对一的关系。

4、可以使用XamlReader.Load创建的对象添加的对象必须是一个可以容纳该子元素的Silverlight对象。

posted @ 2012-01-13 15:49  Nereus_37  阅读(1043)  评论(0编辑  收藏  举报