简体   繁体   中英

WPF Style for Control Library

I have a library ( Styles.DLL ) which contains a collection of keyed WPF Styles .

I have a class library ( Module.DLL ) which contains a number of Windows and UserControls which can be shared across various applications. I use the keyed Styles defined in Styles.DLL to create implicit Styles for the various Controls used on these Windows and UserControls eg Button or ComboBox .

I then have an application ( App.EXE ) in which I use the Windows defined in Module.DLL . I merge the required ResourceDictionaries from Styles.DLL in the App.xaml of App.EXE .

This all works.


My question is: How can I remove the dictionary merging from App.xaml in the hosting application and include it in Module.DLL without having to merge the dictionaries into each Window's resources?

I guess I'm looking for something like an app.xaml file but for a class library...

I use a method that clears the current Dictionaries and merge the ones I want. Actually, the "Clear" has to be set inside at the method invocation, here's an example:

    void AddResourceDictionary(string source)
    {
        ResourceDictionary resourceDictionary = Application.LoadComponent(new Uri(source, UriKind.RelativeOrAbsolute)) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
    }

Implementing a custom Theme/Skin/Resource:

        private void ThemeNameHere()
    {
        Application.Current.Resources.Clear();

        AddResourceDictionary("Computar.Wpf;component/Style/MyStyle.xaml");
        ....

    }

It's been very helpful!

I couldn't find a way to solve this using XAML only. My solution was to merge the required ResourceDictionaries into the Application object in code using the following:

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary
{
    Source = new Uri(@"pack://application:,,,/Styles.DLL;component/Styles.xaml")
});

Hopefully this will help someone who has a similar issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM