XAML Islands を使用してアプリを作成しています。WPF アプリで Windows 10 スタイルを使用したいと考えています。たとえば、次のよう<TextBlock Text="Header" Style="{StaticResource HeaderTextBlockStyle}"/>
になります。
しかし、これは WPF では機能しません (変更を加えることなく UWP で機能します)。私の理解では、XAML Islands がそれを可能にするはずです。上記のコードを xaml ファイルに単純に追加しようとすると、例外が発生します
「HeaderTextBlockStyle」という名前のリソースが見つかりません。リソース名は大文字と小文字が区別されます。
要素に追加すると、同じ例外が発生Style="{StaticResource HeaderTextBlockStyle}"
し<xamlhost:WindowsXamlHost>
ます。
コードでコントロールを追加しようとしたので、この WindowsXamlHost コントロールをスタックパネルとして追加しました。
<xamlhost:WindowsXamlHost InitialTypeName="Windows.UI.Xaml.Controls.StackPanel" ChildChanged="WindowsXamlHost_ChildChanged"/>
そして、追加のコントロール (TextBlock) を StackPanel に追加する処理を行うこのメソッド (コントロールが作成されたときに実行されるイベント ハンドラー。これから学習します) を追加しました。
private void WindowsXamlHost_ChildChanged(object sender, EventArgs e)
{
// Get the host control
WindowsXamlHost host = (WindowsXamlHost)sender;
// Get the StackPanel in the host
Windows.UI.Xaml.Controls.StackPanel sp = (Windows.UI.Xaml.Controls.StackPanel)host.Child;
// Make a TextBlock to add to the StackPanel
Windows.UI.Xaml.Controls.TextBlock textBlock = new Windows.UI.Xaml.Controls.TextBlock();
// Set the text of the TextBlock
textBlock.Text = "LockCursorInMonitor";
// Get the style resources, cast them to the appropriate type for XAML Islands and add them to the TextBlock
textBlock.Style = (Windows.UI.Xaml.Style)Application.Current.Resources["HeaderTextBlockStyle"];
// Another way to get resources but this doesn't work too.
//textBlock.Style = (Windows.UI.Xaml.Style)this.FindResource("HeaderTextBlockStyle");
// Add the TextBlock to the stackpanel
sp.Children.Add(textBlock);
}
このApplication.Current.Resources["HeaderTextBlockStyle"]
方法は何もせず、例外もスローしません。
ウェイは次のthis.FindResource("HeaderTextBlockStyle")
例外をスローします:
System.Windows.ResourceReferenceKeyNotFoundException: ''HeaderTextBlockStyle' リソースが見つかりません.'
では、WPF アプリでこれらのスタイル リソースを取得するにはどうすればよいでしょうか。