5

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>

誰かがより良いアプローチを知っているかもしれません。

ありがとう、ツインハビット

4

1 に答える 1

-1

Application クラスで行うのと同じように、UserControl 内に RD をロードしようとしましたか?

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>                
            <ResourceDictionary Source="WpfControls;Component/GlobalResourceDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

このようにして、ユーザー コントロールで URI を指定するだけで、静的メンバーの煩わしさを完全に回避できます。

ところで、RD が UserControl と同じアセンブリにない場合は、必ず正しい URI 構文を使用してください。例: pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml (パック URI の詳細)

于 2010-09-27T18:57:43.433 に答える