Assembly-wide / root-level styles in WPF class library

Dr. WPF (or the person formerly known as Dr. WPF) has a great post on the subject.

Here's an excerpt from the post where they create the Application object and add resources:

if (Application.Current == null)
{
    // create the Application object
    new Application();

    // merge in your application resources
    Application.Current.Resources.MergedDictionaries.Add(
        Application.LoadComponent(
            new Uri("MyLibrary;component/Resources/MyResourceDictionary.xaml",
            UriKind.Relative)) as ResourceDictionary);
}

Since my assembly is hosted via interop I had to add setting the ShutdownMode as follows and shutdown when finished:

new Application() { ShutdownMode = ShutdownMode.OnExplicitShutdown };

It worked like a charm.


If you dont have an app.xaml, you can still load it into the appplication-level resources, but you have to write code (not xaml) to do it, similar to this...

void LoadIt()
{
     ResourceDictionary MyResourceDictionary = new ResourceDictionary();
     MyResourceDictionary.Source = new Uri("MyResources.xaml", UriKind.Relative);
     App.Current.Resources.MergedDictionaries.Add(  MyResourceDictionary )
}

check out this site for an example: http://ascendedguard.com/2007/08/one-of-nice-features-about-wpf-is-how.html


This sounds like a job for theming.

  1. Add a /themes/generic.xaml ResourceDictionary to your project.
  2. Add the following to AssemblyInfo.cs: [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
  3. ?
  4. Profit!

Any resources you add to generic will be used by all controls. Also you can make profile specific themes (Luna, Aero etc.) by including a ResourceDictionary file with the correct theme name in the themes directory.

Heres a link to more info: Create and apply custom themes


Try adding

Style={DynamicResource MyStyle}

You cannot use a StaticResource in this case.

Tags:

C#

.Net

Wpf

Xaml