成功引用 XamlReader.Load() 加载的文件中的 ResourceDictionary

Bre*_*ant 5 xaml resourcedictionary xamlreader windows-phone-7

我正在构建一个通用的 WP7 程序集,它将显示我的应用程序的通用帮助/有关信息,每个应用程序程序集将指定一对 StackPanel,其中包含一些应用程序特定的信息(我们称为 Legal.xaml 和 WhatsNew.xaml)。

\n\n

理想情况下,这些应用程序特定的 XAML 文件应采用纯文本形式(而不是在代码中实例化的内容),以便可通过 HTTP 加载或作为嵌入式资源字符串加载。

\n\n

加载 XAML 工作正常,直到我尝试将某些样式定义分解到另一个文件中,然后 XamlReader.Load() 失败并显示以下注释: \xe2\x80\x9cAttribute AboutPageDocs/CommonStyles.xaml 值超出范围。[行:43 位置:45]\xe2\x80\x9d

\n\n

加载 Legal.xaml 时会发生该错误,当我们环顾四周时,如 43,我们发现我试图加载现在包含自定义样式的 ResourceDictionary:

\n\n
<StackPanel.Resources>\n    <ResourceDictionary>\n        <ResourceDictionary.MergedDictionaries>\n            <ResourceDictionary Source="AboutPageDocs/CommonStyles.xaml"/>\n        </ResourceDictionary.MergedDictionaries>\n    </ResourceDictionary>\n</StackPanel.Resources>\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是错误的...如果简单地复制并粘贴 StackPanel 代码(在运行时动态加载)并将其放入 UserControl 中...一切工作正常。

\n\n

不需要在 Legal.xaml 和 WhatsNew.xaml 中内联定义我的样式...有没有办法让 XamlReader.Load() 属性查找 CommonStyles.xaml?

\n\n

考虑到源路径不正确,我尝试通过两个程序集将 CommonStyles.xaml 的副本放置在不同位置...并尝试使用 pack:// uri 语法...到目前为止都无济于事。

\n\n

我缺少什么?

\n

Sev*_*ven 2

当我意识到 XamlReader 能够在指定为绝对路径时解析引用的 XAML 文件时,我寻找指定自己的上下文的可能性。

当我在调用 XamlReader.Load() 时指定 ParserContext 时,我发现这对我有用

public static FlowDocument ReadFlowDocument( FileInfo xamlFile )
{
    // Specify a ParserContext.
    // It's important to set BaseUri to the file itself
    // not to its parent direcory!
    ParserContext parserContext = new ParserContext();
    parserContext.BaseUri = new Uri( xamlFile.ToString() );

    // Create a stream from this file
    FileStream stream = new FileStream( xamlFile.ToString(), FileMode.Open );

    // Let the XamlReader load and parse the XAML. It will resolve any referenced ResourceDirectories
    // specified with a relative path
    return (FlowDocument) XamlReader.Load( stream, parserContext );
}
Run Code Online (Sandbox Code Playgroud)