silverlight将字符串转化为控件
silverlight的System.Windows.Markup命名空间下,提供了XamlReader.Load()方法可以将字符串转换为控件。
代码
StringBuilder sbGrid = new StringBuilder();
sbGrid.Append("<Grid Width=\"150\" Height=\"150\" Background=\"Red\" ");
sbGrid.Append(" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"");
sbGrid.Append(" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">");
sbGrid.Append("</Grid>");
Grid grid = (Grid)XamlReader.Load(sbGrid.ToString());
LayoutRoot.Children.Add(grid);
效果:

注意:通过拼接字符串添加silverlight自带的控件时,务必加上
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
命名空间字符串,否则会提示无法找到命名空间。如果添加的是第三方的控件,可不用添加上述字符串,但必须加上控件的命名空间。比如:添加一个第三方的按钮
代码
StringBuilder sbButton = new StringBuilder();
sbButton.Append(" <telerik:RadButton xmlns:telerik=\"http://schemas.telerik.com/2008/xaml/presentation\" ");
sbButton.Append(" Width=\"150\" Height=\"50\" Content=\"My Button\" />");
RadButton radButton = (RadButton)XamlReader.Load(sbButton.ToString());
LayoutRoot.Children.Add(radButton);
效果:


浙公网安备 33010602011771号