【发布时间】:2020-10-29 02:28:27
【问题描述】:
我的应用程序有一项功能,它涉及保存一些已创建的 UI 元素,以便在用户下次启动应用程序时重新创建它们。
为此,它使用 XamlWriter.Save 函数保存 UI 元素对象,然后将该字符串保存到 XML 文件中。我可以成功找回它保存的字符串。
例如,这是一个被序列化并保存的按钮:
<Button Name="Thumb1" Grid.Column="0" Grid.Row="0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:swi="clr-namespace:System.Windows.Interop;assembly=PresentationCore" xmlns:s="clr-namespace:System;assembly=mscorlib"><Button.Tag><s:Int32>0</s:Int32></Button.Tag><Image Stretch="UniformToFill" Width="380" Height="213" HorizontalAlignment="Center" VerticalAlignment="Center"><Image.Source><swi:InteropBitmap /></Image.Source></Image></Button>
但是,当我尝试使用以下代码重新加载此数据时,我收到 XamlParseException,它表示“根级别的数据无效。第 1 行,位置 1。”
using (StringReader SR = new StringReader(Attribute) )
{
using (XmlReader XR = XmlReader.Create(SR) )
{
InMedButton = (System.Windows.Controls.Button)XamlReader.Load(XR);
}
};
这是我从 Microsoft 文档获得的代码 sn-p:https://docs.microsoft.com/en-us/dotnet/api/system.windows.markup.xamlwriter?view=netcore-3.1
我觉得它可能没有正确序列化 XAML,因为它没有像 XML 或 XAML 通常那样以树状结构格式化,但我不知道。
如何正确反序列化和加载 XAML?
【问题讨论】:
-
你必须按照你写数据的相反顺序阅读。写代码和读代码不一致。
-
您应该首先将您的 ui 创建为字符串,然后 xamlreader.parse 将其转换为 ui。然后,您可以将字符串保存到磁盘上的文件中。 Xamlwriter 保存有一些严重的限制。
-
@jdweng 不幸的是,反转字符串并没有解决它。我确实看到了 w/r 代码之间的区别。当写入 XML 时,像 > 或 " 之类的某些字符的编码方式不同。我想修复的函数可能会起作用
-
@Andy 如何将其设为字符串?
-
我没有说反转字符串。
标签: c# xml wpf xaml xamlreader