TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

Programmatically add to Window.Resources in WPF

Is there a way to add a ResourceDictionary at the Window level instead of the Application level?

I see many examples for something like this:

Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);

However, nothing like what I would expect there to be, such as:

Window.Resources.MergedDictionaries.Add(myResourceDictionary);

Thanks in advance,

Upvotes: 5

Views: 7613

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

You can't do:

Window.Resources

However, you can do:

this.Resources.MergedDictionaries.Add(myResourceDictionary);

Resources is a property of FrameworkElement, and is shared by Application and Window (and most other user interface classes in WPF). However, it is an instance property, not a static property, so you need to work with the resources of a specific instance. When you typed "Window.Resources" you were trying to add to the "window" type, not to a specific Window.

This works in your Application line since Application.Current returns the current instance of an Application, so you're working with the correct, specific instance (not the type).

Upvotes: 8

Related Questions