Read WPF ResourceDictionaries from WinForms
Question
Is it possible to read WPF ResourceDictionaries from WinForms? If yes, how?
Solution
When you add resources dictionaries to an WPF project the build action is automatically set to Page. This means that the compiler generates a BAML stream and adds it to the resources of the assembly.
Since WPF has the built-in functionality to read a BAML stream but its API is not public, we have to write a little helper class that access the internal method over reflection.
public static class BamlReader
{
public static object Load(Stream stream)
{
ParserContext pc = new ParserContext();
MethodInfo loadBamlMethod = typeof(XamlReader).GetMethod("LoadBaml",
BindingFlags.NonPublic | BindingFlags.Static)
return loadBamlMethod.Invoke(null, new object[] { stream, pc, null, false });
}
}
// Usage:
StreamResourceInfo sri = System.Windows.Application.GetResourceStream(
new Uri("/MyAssemblyName;component/MyResourceDict.xaml", UriKind.Relative));
ResourceDictionary resources = (ResourceDictionary)BamlReader.Load(sri.Stream);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow