0

我试图解决的理想情况是这样的:

  1. MyCompany.Styles.dll 程序集中定义了一组常用样式。

  2. MyCompany.Controls.dll 程序集中有一组自定义控件使用 MyCompany.Styles.dll 程序集中的样式。

  3. 任何使用 MyCompany.Controls.dll 程序集中的控件的应用程序都不需要在应用程序的 app.xaml 中引用 MyCompany.Styles.dll 程序集中的任何 ResourceDictionary,但只要样式被引用并且由 MyCompany.Controls.dll 程序集使用。

这可能吗?如果可以,怎么做?

非常感谢,尤金

4

1 回答 1

0

这是可能的,所以我为任何偶然发现我原来的问题的人发布了解决方案。

修复方法是将所需样式合并到 MyCompany.Controls.dll 程序集中每个自定义控件的 ResourceDictionary 中。虽然我在 XAML 中没有成功执行此操作,但只需将以下调用添加到每个自定义控件的构造函数中:

this.MergeInResources("/MyCompany.Styles;component/default.xaml");

神奇的扩展方法如下:

    /// <summary>
    /// Loads the resources pointed to by the (relative) path
    /// <paramref name="resourcePath"/> into the Merged Dictionaries
    /// of <paramref name="control"/>.
    /// </summary>
    internal static void MergeInResources(this FrameworkElement control,
                                          string resourcePath)
    {
        if (String.IsNullOrWhiteSpace(resourcePath))
            throw new ArgumentNullException("resourcePath");

        Uri uri = new Uri(resourcePath, UriKind.Relative);
        ResourceDictionary dictionary = (ResourceDictionary)Application.LoadComponent(uri);
        control.Resources.MergedDictionaries.Add(dictionary);
    }

错误处理和 ResourceDictionary 缓存 + 共享留给读者。

于 2012-10-03T16:42:55.290 回答