我浏览了大量类似的帖子,但在我的情况下似乎没有任何效果。我要做的就是加载一个 xaml 文件(位于其他程序集中),并遍历不同的元素/对象以检查某个属性值。我可以将它作为一个简单的 XML 文件来阅读,但是无法通过 xml 解析来捕获样式等内容。经过大量搜索,我尝试了以下两件事:
- 我
x:Class=".."
从 xaml 中删除了我还添加了assembly=XBase.UI
这个(因为我原来的 xaml 没有这个,我读到动态加载时,你需要知道指定程序集)然后我将剩余的文件加载为 xml 流。然后我打电话给 XamlReader.Load(stream)
这似乎适用于发布查询的人,但我得到了例外
'System.Windows.Markup.XamlParseException : 'The invocation of the constructor on type 'XBase.UI.XControlBase' that matches the specified binding constraints threw an exception.' Line number '6' and line position '55'.
----> System.InvalidOperationException : The calling thread must be STA, because many UI components require this.'
我尝试的第二件事是使用 XamlReader.Parse 并提供 ParserContext。这就是我所做的:
var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[] { });
context.XamlTypeMapper.AddMappingProcessingInstruction("UI", "XBase.UI", ""); //assemblyname is empty as my original file doesn't have one
context.XmlnsDictionary.Add("UI", "clr-namespace:XBase.UI;assembly=XBase.UI");
string text = File.ReadAllText(xamlfile);
var object = XamlReader.Parse(xamlfile, context);
这也会引发异常:
'System.Windows.Markup.XamlParseException : 'Cannot create unknown type '{clr-namespace:XBase.UI}XControlBase'.' Line number '1' and line position '2'.
----> System.Xaml.XamlObjectWriterException : 'Cannot create unknown type '{clr-namespace:XBase.UI}XControlBase'.' Line number '1' and line position '2'.'
我的原始 xaml 文件
<UI:XControlBase x:Class="XBase.UI.XListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:UI="clr-namespace:XBase.UI" Height="Auto" Width="Auto" IsTabStop="False"
mc:Ignorable="d"
Visibility="{Binding IsVisible, Converter={StaticResource VisibilityConverter}}">
<UI:XControlBase.Resources>
<UI:ButtonTemplateSelector x:Key="ButtonSelector" />
</UI:XControlBase.Resources>
<UI:ItemControlWrapper
ItemsSource="{Binding ButtonList}"
ItemTemplateSelector="{StaticResource ButtonSelector}"
IsTabStop="False">
<UI:ItemControlWrapper.ItemsPanel>
<ItemsPanelTemplate >
<StackPanel Orientation="{Binding ListOrientation}" />
</ItemsPanelTemplate>
</UI:ItemControlWrapper.ItemsPanel>
</UI:ItemControlWrapper>
</UI:XControlBase>
请帮帮我。我什至不确定这是否是实现我想要的正确方法。如果除了 XmlDocument 的 GetElementsByTagName 之外,还有其他方式可以以更有意义的方式列出某种类型的所有元素,请告诉我。
提前致谢!