I have a couple different applications where this would be helpful, but for the sake of a concrete example, let us suppose I have a WinForms application.
This application makes use of WPF controls within ElementHost objects. I now would like to define an implicit style for all WPF Buttons (System.Windows.Controls.Button) so that every ElementHost does not need to merge in the resource dictionary nor does every Button need to explicitly specify the style.
Where do I define said style?
I have tried creating the resource dictionary Themes\Generic.xaml in the project root and specifying
[assembly: ThemeInfo(
ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly )]
in the AssemblyInfo.cs. This did not work and I am under the impression that that styles there are only for custom controls defined in the same assembly, where as Button is defined in a foreign assembly.
Examples place implicit style code in <Application.Resources>; however, that node is with-in App.xaml, which (the project not having started its life as a WPF application) does not exist. Is it possible to add an App.xaml or is there some other place to put <Application.Resources> such that they are recognized?
Dr WPF has several suggestions:
http://drwpf.com/blog/2007/10/05/managing-application-resources-when-wpf-is-hosted/
Some relevant parts quoted below:
Create an Application Instance and Add Resources in Code
Below is a very simple function that will create the Application object if it does not exist and then load some resources:
Now you just need to make sure that you call this function prior to parsing any XAML files that contain static resource references to application-level resources. To do this, simply add a call to the above function in the constructor of your markup-based classes before any call to
InitializeComponent():Define the Application Class in XAML and Create It on the Fly
First, we do not want MSBuild to generate an application entry point for our Application class. So instead of declaring the
App.xamlfile as anApplicationDefinitionelement in the project file, we need to declare it as aPageelement:Next, we need to make sure that our
App.xamlmarkup is parsed. Typically, this is done as part of the entry point function (which we just eliminated). Instead, we can simply define a constructor for theApplicationclass and callInitializeComponentdirectly:Now all our resources and merged dictionaries can be declared in
App.xamland our static function to load the Application instance can be as simple as this:Manage a Collection of Resource Dictionaries in Code and Merge them at the Element Level
In this scenario, we do not leverage an
Applicationobject at all. Instead, we dynamically load eachResourceDictionaryat runtime and selectively merge it into pages or windows or specific elements, as necessary.This would allow us to merge in shared resource dictionaries to the Resources collection of any framework element, by simply doing this: