【问题标题】:Is it possible to use styles in an external assembly without merging them into the ResourceDictionary of app.xaml?是否可以在外部程序集中使用样式而不将它们合并到 app.xaml 的 ResourceDictionary 中?
【发布时间】:2012-10-02 01:10:31
【问题描述】:

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

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

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

  3. 任何使用 MyCompany.Controls.dll 程序集中的控件的应用程序都不需要在应用程序的 app.xaml 中引用 MyCompany.Styles.dll 程序集中的任何 ResourceDictionary,但样式只会解析给定事实上,它们被 MyCompany.Controls.dll 程序集引用和使用。

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

非常感谢,尤金

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

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

    解决方法是将所需样式合并到 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缓存+共享留给读者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多