如何在VS2010中的不同程序集和设计时支持中使用ResourceDictionary

时间:2012-07-26 11:57:14

标签: wpf visual-studio-2010 resourcedictionary design-time

我有以下问题。我有ResourceDictionaries位于不同的程序集中。如果我创建UserControl并使用此ResourceDictionaries中的Styles和Resourcen,则所有在运行时上工作正常,但在设计时我在vs2010中遇到错误 - 无法找到名为“InvertConverter”的资源。

  • CoreResource.dll
  • OtherResource.dll
  • UserControl.dll(参考上面两者)
  • OtherWpf.dll(以上所有参考并使用usercontrols)

现在我查了很多关于这个问题的帖子和博客。一种解决方案是将ResourceDictionaries添加到每个UserControl中 - 这可以工作但在运行时会产生大量开销。我找到的所有其他解决方案对我都不起作用。

我会将我在leat上所做的事作为答案发布,因为它对我有用。但我希望看到其他/更好的解决方案。

1 个答案:

答案 0 :(得分:0)

这就是我现在所做的。

我只是使用静态方法在设计时添加我的资源。

public class DesignTimeResourceLoader
{
    public static void LoadResources4DesignTime(UserControl ctrl)
    {
        //do this just in DesignMode
        if (Convert.ToBoolean(DesignerProperties.IsInDesignModeProperty.GetMetadata(ctrl).DefaultValue))
        {
            var uricore = new Uri("/CoreResource;component/ResourceDictionary.xaml", UriKind.Relative);
            var core = (ResourceDictionary)Application.LoadComponent(uricore);
            ctrl.Resources.MergedDictionaries.Add(core);

            var uriother = new Uri("/OtherResource;component/OtherResourceDictionary.xaml", UriKind.Relative);
            var other = (ResourceDictionary)Application.LoadComponent(uriother);
            ctrl.Resources.MergedDictionaries.Add(other);

            //if you have(need more just add here
        }
    }
}

我在UserControl.dll中创建并使用此类,并且对于每个Usercontrol,我都会在构造函数中调用该方法。

public partial class MyControl : UserControl
{
    public MyControl ()
    {
        DesignTimeResourceLoader.LoadResources4DesignTime(this);
        InitializeComponent();
    }
}

这对我来说很有用。也许我现在没有看到一些缺点。