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

时间:2011-12-06 01:25:20

标签: xaml windows-phone-7 resourcedictionary xamlreader

我正在构建一个通用的WP7程序集,它将显示我的应用程序的常见帮助/关于信息,每个应用程序程序集将指定一对StackPanels,其中包含一些应用程序特定信息(很好地调用em Legal.xaml和WhatsNew.xaml )。

理想情况下,这些特定于应用程序的XAML文件应采用纯文本格式(与代码中实例化的内容相比),因此可通过HTTP加载或作为嵌入式资源字符串加载。

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

加载Legal.xaml时会发生错误,当我们四处查看时,我们会发现我在尝试加载现在包含自定义样式的ResourceDictionary:

<StackPanel.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="AboutPageDocs/CommonStyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</StackPanel.Resources>

这是bugger ...如果只是复制&amp;粘贴StackPanel代码(在运行时动态加载)并将其放入UserControl ......工作正常。

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

考虑到源路径不正确,我尝试通过两个程序集将CommonStyles.xaml的副本放在不同的位置......以及使用pack:// uri语法进行试验......全部为no到目前为止。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

当我意识到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 );
}