XamlReader - 将多个CLR命名空间映射到单个XML命名空间

3

我有一个WPF项目,其中包含一个AssemblyInfo.cs文件,把多个CLR命名空间分组成一个单独的XML命名空间:

[assembly: XmlnsDefinition("http://foo.bar", "MyLibary.Controls")]
[assembly: XmlnsDefinition("http://foo.bar", "MyLibary.Converters")]

在 XAML 中,它的使用方法如下:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:fb="http://foo.bar">
    <fb:FooButton IsEnabled="{Binding Something, Converter={fb:FooConverter}}"/>
</UserControl>

当XAML被正常实例化时,这很有效,但现在我正在尝试使用XamlReader从我的项目中动态加载XAML文件。

问题在于:我似乎无法将多个CLR命名空间映射到单个XML命名空间。似乎最后添加到XamlTypeMapper中的定义是唯一持久存在的(例如,它覆盖了先前的注册):

var parserContext = new ParserContext();
parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
parserContext.XmlnsDictionary.Add("fb", "http://foo.bar");

parserContext.XamlTypeMapper = new XamlTypeMapper(new string[] {"MyLibrary"});
parserContext.XamlTypeMapper.AddMappingProcessingInstruction("http://foo.bar", "MyLibrary.Converters", "MyLibrary");
parserContext.XamlTypeMapper.AddMappingProcessingInstruction("http://foo.bar", "MyLibrary.Controls", "MyLibrary");

...

var rootNode = XamlReader.Load(memeoryStream, parserContext) as FrameworkElement

错误信息是:
'Cannot create unknown type '{http://foo.bar}MyConverter'.'

如果我将所有代码放在一个公共的CLR命名空间下,一切都可以正常工作,但不幸的是这不是一个选项。有人将多个CLR命名空间映射到一个XML命名空间,以便动态加载XAML内容吗?
提前致谢!

1
这个MSDN论坛帖子表明,为了让多个CLR命名空间正常工作,程序集需要被实际加载。 - Rick Sladkey
谢谢,我没有看到那个线程。删除所有对AddMappingProcessingInstruction的调用,并在XamlReader.Load()之前使用Assembly.Load()似乎解决了问题。 - FunnyItWorkedLastTime
1个回答

5

如上面的评论所述,解决方案是在调用XamlReader.Load之前手动加载程序集,并完全删除类型映射器和上下文:

Assembly.Load("MyLibrary");
var rootNode = XamlReader.Load(memeoryStream) as FrameworkElement

我本以为由于XamlTypeMapper是用一系列程序集进行初始化的,所以这个类将负责加载程序集(也许确实是这样),但是AddMappingProccessingInstruction的行为阻止了这种工作方式的实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接