Freigeben über


Dynamically loading loose XAML for styles in WPF

I was asked for a sample of how to do this and it is not difficult, but since someone asked I thought I'd go ahead and drop it out here, because it might show up in someone's search result and help.

The problem was that the person with whom I was working wanted to be able to add new XAML files to control style and layout without having to compile them into the app, into .baml, or into a dll.  This would give them the ultimate flexibility of controlling the theme of the application completely via the app.config and whatever loose XAML they wanted/needed to add.  The code to do this is pretty simple.  Borrowing a friend and coworkers sample I modified it slightly to not compile the XAML into the app and to copy the file.

 Assuming you have a means of determining what XAML you might like to load the code in free-form (and rather verbos) would be something of this nature:

ResourceDictionary currentSkin;

...

Collection<ResourceDictionary> appResources;

//grab a shortcut to MergedDictionaries

appResources = App.Current.Resources.MergedDictionaries;

ResourceDictionary skin = new ResourceDictionary();

//The next two lines are the key to loading the loose XAML to use as a resource

Uri skinUri = new Uri(@"[path to XAML]", UriKind.RelativeOrAbsolute);

skin.Source = skinUri;

//currentSkin will have been previously assiged

appResources.Remove(currentSkin);

// Store new skin

currentSkin = skin;

// If new skin specified, apply it

if (skin != null)

{

appResources.Add(skin);

}

 So, as you can see it is a pretty simple endeavor to dynamically load loose XAML and use it as a resource dictionary.

Comments