从WinForms中读取WPF ResourceDictionaries

时间:2009-05-02 09:40:22

标签: wpf winforms resources

是否可以从WinForms中读取WPF ResourceDictionaries?如果是,怎么样?

1 个答案:

答案 0 :(得分:1)

将资源字典添加到WPF项目时,构建操作会自动设置为Page。这意味着编译器生成BAML流并将其添加到程序集的资源中。

由于WPF具有读取BAML流的内置功能,但其API不是公共的,因此我们必须编写一个辅助类来访问反射内部方法。

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);

来源:How to read WPF ResourceDictionaries from WinForms