私は同様の投稿をたくさん見ましたが、私の場合は何もうまくいかないようです。私がしたいのは、(他のアセンブリにある) xaml ファイルをロードし、さまざまな要素/オブジェクトを反復処理して、特定の属性値をチェックすることだけです。単純な XML ファイルとして読み取ることもできましたが、スタイルなどは xml 解析では把握できません。いろいろ調べた結果、以下の2点を試しました。
- xaml からを削除し、これ
x:Class=".."
にも を追加し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.'
2 番目に試みたのは、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 以外に、特定の種類のすべての要素をより意味のある方法で一覧表示する別の方法がある場合は、お知らせください。
前もって感謝します!