Sometimes it’s useful to add a Style programmatically to a CustomControl.
This part is very easy. You just have to allocate the Style in the Constructor of that Control:
[code lang="csharp"]Style = (Style)Application.Current.Resources["BrowserWindowStyle"];[/code]
This Style is placed in the Current resources of the Application. But what do you do, if you need a default Style which is not in the resources of your application? What do you do, if you don’t want to write the Style in C# directly in the Source of your Control?
You can add a XAML file with a ResourceDictionary to your Library. Maybe called “BrowserWindowStyle.xaml”
You can Load the XAML file as a ResourceDictionary object and add them to the MergeDictionaries of your current Application:
[code lang="csharp"]public BrowserWindow()
{
var dic = ResourceHandler.ResolveResourceDictionaryByPath<BrowserWindow>("Dialogs/BrowserWindowStyle.xaml");
if (!Application.Current.Resources.MergedDictionaries.Contains(dic))
{
Application.Current.Resources.MergedDictionaries.Add(dic);
}
Style = (Style)Application.Current.Resources["BrowserWindowStyle"];
}[/code]
Really simple, if you know how to do that
The ResourceHandler is a small class which provides useful static methods to resolve resource paths:
[code lang="csharp"]public static ResourceDictionary ResolveResourceDictionaryByPath<T>(string path)
{
var namespacePath = typeof(T).Assembly.ToString().Split(',')[0];
var uri = new Uri(string.Format("/{0};component/{1}", namespacePath, path), UriKind.RelativeOrAbsolute);
return new ResourceDictionary { Source = uri };
}[/code]