使用 XamlReader 使用 xml:space=“preserve” 加载 xaml 时出现奇怪的问题
本文关键字:使用 问题 xaml xml XamlReader space preserve 加载 | 更新日期: 2023-09-27 18:33:20
当使用 XamlReader 从预定义的 xaml 文件加载我的应用程序的菜单时,我发现了一个非常奇怪的问题。我需要定义xml:space="preserve"
的属性,xaml 是这样的:
<m:MenuManager>
...
<m:Resource>
<m:Resource.ResourceTitle>
<sys:String xml:space="preserve">Click the Button
(InvokeCommandAction)
View</sys:String>
</m:Resource.ResourceTitle>
</m:Resource>
...
</m:MenuManager>
将 xaml 内容加载到字符串中,并使用 XamlReader.Load
将其转换为菜单管理器对象。第一次调用 XamlReader.Load
方法时,只会返回标签<sys:String xml:space="preserve">
内的单词,并且预期的结果只会在第二次返回。
var uri = new Uri("/Sample;component/Assets/Menu.xaml", UriKind.Relative);
var info = Application.GetResourceStream(uri);
string xaml = null;
using (StreamReader reader = new StreamReader(info.Stream))
{
xaml = reader.ReadToEnd();
}
//when the first time load, only a string value of
//"Click the Button
(InvokeCommandAction)
View" is returned
var temp1 = XamlReader.Load(xaml);
//when the second time load, all menu content loaded successfully and
//converted to the object of MenuManager
readXaml = XamlReader.Load(xaml) as MenuManager;
当我删除属性xml:space="preserve"
或将其更改为xml:space="default"
时,它将正常工作,并且我可以通过仅调用一次方法XamlReader.Load
来获取 MenuManager 的对象。但我真的需要在我的页面上保留空格,这里的代码看起来很奇怪。谁能解释一下?谢谢!
如果您不想向所有元素添加xml:space="preserve"
,则可以使用此附加参数来XamlReader.Load
:
XamlReader.Load(xaml, new ParserContext() { XmlSpace = "preserve" });