我已经找到了解决这个问题的方法,只需付出很少的努力即可实现。
首先为资源字典添加一个代码隐藏文件 GlobalResources.xaml.cs:
namespace YourNamespaceHere
{
partial class GlobalResources : ResourceDictionary
{
public GlobalResources()
{
InitializeComponent();
}
}
}
然后将 x:Class 属性设置为 GlobalResources.xaml 中的 ResourceDictionary 标记:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="YourNamespaceHere.GlobalResources">
您现在可以像这样创建资源字典的实例:
new YourNamespaceHere.GlobalResources()
在使用资源字典的 WPF 用户控件中,将以下内容添加到 UserControl1.xaml.cs 的构造函数中:
public UserControl1()
{
if (DesignerProperties.GetIsInDesignMode(this))
this.Resources.MergedDictionaries.Add(new YourNamespaceHere.GlobalResources());
InitializeComponent();
}
现在,使用 UserControl1 的控件的 WinForms 设计器将不再抱怨找不到包含资源字典的 dll。使用的资源也将显示在设计器中。
为了确保 WPF 设计器将显示 UserControl1 中使用的资源字典中的内容,您仍然需要在 UserControl1.xaml 中添加以下内容:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MyDll;component/GlobalResources.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
MyDll 是包含资源字典的程序集的名称。在此示例中,GlobalResources.xaml 和 GlobalResources.xaml.cs 应放置在程序集的根级别(而不是文件夹中)。