在silverlight 2 中,有时候会遇到使用XmlWriter写到Xml文件,然后使用XamlReader动态加载此xml文件(作为Xaml代码加载)。 和1.1版本不同的是,在silverlight 2中使用XamlReader.Load()时,加载的xaml代码需要带有默认的命名空间: xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
不同的是,这个命名空间不能使用WriteAttributeString()来写, 这条语句会引发下面的错误:
writer.WriteAttributeString("xmlns",
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"); //错误
用户代码未处理 XmlException
在同一开始元素标记中,无法将前缀“”从“”重定 义为“http://schemas.microsoft.com/winfx/2006/xaml/presentation”。 而如果在WriteStartElement中直接定义命名空间,如下,也会引起错误。 writer.WriteStartElement("xmlns","Canvas",
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"); //错误 这条语句会引发下面的错误: 用户代码未处理 ArgumentException
前缀“xmlns”保留给 XML 使用。 说明这两种方法都不行。最后想到,既然xmlns是默认的命名空间,那么在WriteStartElement()的时候不写“命名空间前缀 xmlns”,这样不就可以了。一试,果然可以。 writer.WriteStartElement("Canvas", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); //正确
另外遇到的一个问题就是,在输出的StringBuilder.ToString()的字符串中带有”xml声明”,这个比较好解决。只要实例一个XmlWriterSetting,然后设置XmlWriterSetting.OmitXmlDeclaration=true 即可省略xml声明。
完整的示例代码如下: 按 Ctrl+C 复制代码
按 Ctrl+C 复制代码 后台代码:
public partial class p241_2 : UserControl { public p241_2() { InitializeComponent(); start();//调用输出的函数 } private void start() { StringBuilder xamlString = new StringBuilder();//XmlWriter输出的字符串 XmlWriterSettings setting = new XmlWriterSettings();//XmlWriter的功能设置 setting.OmitXmlDeclaration = true; //为true 则省略xml声明 using (XmlWriter writer = XmlWriter.Create(xamlString, setting)) { WriteXml(writer);//使用writer写入具体的数据 } string ts = xamlString.ToString();//获取StringBuilder生成的字符串 //XamlReader.Load():分析格式良好的 XAML 片段并创建相应的 Silverlight 对象树,然后返回该对象树的根 FrameworkElement d = (FrameworkElement)XamlReader.Load(ts); pCanvas.Children.Add(d as UIElement);//前台xaml代码中有个Canvas,Name为pCanvas } private void WriteXml(XmlWriter writer) { writer.WriteStartElement("Canvas","http://schemas.microsoft.com/winfx/2006/xaml/presentation"); //writer.WriteStartElement("xmlns","Canvas", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); //错误的 // writer.WriteAttributeString("xmlns", null, "http://schemas.microsoft.com/winfx/2006/xaml/presentation");//错误的 //写入xmln:x="http://schemas.microsoft.com/winfx/2006/xaml" 命名空间 writer.WriteAttributeString("xmlns", "x", null, "http://schemas.microsoft.com/winfx/2006/xaml"); //写入一个属性字符串 writer.WriteAttributeString("Canvas.Left", "5"); //写入一个TextBlock writer.WriteStartElement("TextBlock"); writer.WriteAttributeString("Text", "ddddddddd"); writer.WriteEndElement(); writer.WriteEndElement(); } } |
|
来自: 泉水930 > 《silverlight》