5

我有一个 WPF 控件,我想在我的 WinForms 应用程序(使用 ElementHost)中的多个位置(=> 此控件的多个实例)中使用它。

此外,我希望我的 UserControl 的所有实例共享一个 ResourceDictionary 的单个实例。

在 WPF 应用程序中,我可以通过在应用程序资源中合并我的 ResourceDictionary 来实现。

但是,我不想在我的 WinForms 应用程序中创建 WPF 应用程序实例。相反,我正在寻找另一种方式。

我找到了一个解决方案,但我希望您知道一种不需要任何代码的更好方法:

    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 回答