gpt4 book ai didi

c# - "Prefix ' x ' does not map to a namespace"

转载 作者:太空狗 更新时间:2023-10-29 19:44:33 24 4
gpt4 key购买 nike

我想在运行时使用 XamlReader 加载 DataTemplate,但它抛出异常“前缀‘x’未映射到命名空间。”

这是我传递给 XamlReader 的 XML 字符串:

<xm:ResourceDictionary 
xmlns:xm="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:do="clr-namespace:MyLibrary.DataObjects;assembly=MyLibrary.DataObjects"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<xm:DataTemplate DataType="{x:Type do:ValidationResponse}">
<xm:StackPanel Orientation="Horizontal">
<xm:Label>MessageID</xm:Label>
<xm:TextBox Text="{Binding Path=MessageID}"/>
</xm:StackPanel>
</xm:DataTemplate>
</xm:ResourceDictionary>

这是读取它的代码:

ResourceDictionary dictionary = XamlReader.Parse(myXamlString) as ResourceDictionary;

有趣的是,如果我将 x:Key="ValidationResponseTemplate" 添加到 DataTemplate,它会毫无异常(exception)地解析。但是,我不能保持这种方式,因为我无法在程序自己的 .xaml 中通过键指定 DataTemplate(在运行时获取模板之前,它不会知道模板) .

x 命名空间在程序自己的 .xaml 和我试图解析的 XML 片段中定义。

总体目标:能够提供新的数据模板以在运行时更改显示的外观,并显示客户端在编译时不知道的 XML 数据。

最佳答案

找到了解决方法:与其让 XamlReader 解析字符串,不如给它一个 XmlReader,效果会更好。在其中定义了 DataTemplate 的 XML 片段是一个更大的 XML 文档的一部分,该文档的所有 namespace 都在其根目录中定义。这已被读入 XDocument,我从中获取了 XElement,其中定义了 ResourceDictionary。新代码是 MainWindow.xaml.cs 的一部分,如下所示:

ResourceDictionary dictionary = XamlReader.Load(myXElement.CreateReader()) as ResourceDictionary;
this.Resources.MergedDictionaries.Add(dictionary);

这引发了一个不同的异常,它无法解析 (http://myschemas/MyProfile)Binding 的类型。事实证明,您需要限定一切 的 namespace ,包括{Binding ...} 引用。因此必须将 XML 片段修改为:

<xm:TextBox Text="{xm:Binding Path=MessageID}"/>

现在 XamlParser 知道 Binding 是“http://schemas.microsoft.com...”命名空间中的一种类型。

关于c# - "Prefix ' x ' does not map to a namespace",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5641539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com