WinForms アプリケーションで (ElementHost を使用して) いくつかの場所 (=> このコントロールの複数のインスタンス) で使用したい WPF コントロールが 1 つあります。
さらに、UserControl のすべてのインスタンスで、ResourceDictionary の 1 つのインスタンスを共有したいと考えています。
WPF アプリケーションでは、ResourceDictionary をアプリケーション リソースにマージすることでそれを実現します。
ただし、WinForms アプリケーションで WPF アプリケーション インスタンスを作成したくありません。代わりに、別の方法を探しています。
私は1つの解決策を見つけましたが、コードビハインドを必要としないより良い方法を知っていることを願っています:
public static class StaticRDProvider
{
static ResourceDictionary rd;
static StaticRDProvider()
{
var uri = new Uri("WpfControls;Component/GlobalResourceDictionary.xaml", UriKind.Relative);
rd = (ResourceDictionary) Application.LoadComponent(uri);
}
public static ResourceDictionary GetDictionary
{
get { return rd; }
}
}
ユーザー コントロール.xaml.cs:
public partial class MyCustomUserControl : UserControl
{
public MyCustomUserControl()
{
Resources.MergedDictionaries.Add(StaticRDProvider.GetDictionary);
InitializeComponent();
}
}
それはうまくいきます。しかし、私は XAML でのみ機能するソリューションを好みます。さらに、StaticResources を使用できるようにしたいと考えています。したがって、コントロールの初期化後に静的 ResourceDictionary を Controls MergedDictionaries に追加することはできません。
次のことを試しましたが、奇妙な「スタックが空です」という例外がスローされます。
<UserControl x:Class="WpfControls.MyCustomUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:WpfControls="clr-namespace:WpfControls" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<x:Static Member="WpfControls:StaticRDProvider.GetDictionary"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
</Grid>
誰かがより良いアプローチを知っているかもしれません。
ありがとう、ツインハビット