使用SilverLight动态加载控件XamlReader.Load的使用
1.生明一个StringBuilder用于连接字符串
2.创建命名空间(以及相应属性);
2.创建控件使用XamlReader.Load
3.加载到面板上面
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.Text;
- using System.Windows.Markup;
- namespace sl19
- {
- public partial class MainPage : UserControl
- {
- public MainPage()
- {
- InitializeComponent();
- ////textBlock里面的文本
- StringBuilder xaml = new StringBuilder();
- xaml.Append("<TextBlock ");
- xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
- xaml.Append("Canvas.Left=\"50\" Canvas.Top=\"30\" FontSize=\"50\" ");
- xaml.Append(" FontWeight=\"Bold\" Text=\"动态创建XAML对象\" />");
- //创建textBlock
- TextBlock textBlock = (TextBlock)XamlReader.Load(xaml.ToString());
- parentCanvas.Children.Add(textBlock);
- //line的xaml文本
- xaml= new StringBuilder();
- xaml.Append("<Line Stroke=\"Red\" ");
- xaml.Append("xmlns=\"http://schemas.microsoft.com/client/2007\" ");
- xaml.Append(" X1=\"30\" Y1=\"30\" ");
- xaml.Append(" X2=\"200\" Y2=\"200\" StrokeThickness=\"3\" />");
- //创建LINE对象
- Line line = (Line)XamlReader.Load(xaml.ToString());
- parentCanvas.Children.Add(line);
- }
- }
- }
总结:很简单的案例,但是自己按人家写出来发现也有点困难。