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

已成功引用XamlReader.Load()加载的文件中的ResourceDictionary,xaml,windows-phone-7,resourcedictionary,xamlreader,Xaml,Windows Phone 7,Resourcedictionary,Xamlreader,我正在构建一个通用WP7程序集,它将显示我的应用程序的通用帮助/关于信息,每个应用程序程序集将指定一对堆栈面板,其中包含一些特定于应用程序的信息(我们称之为em Legal.xaml和WhatsNew.xaml) 理想情况下,这些特定于应用程序的XAML文件应该是纯文本形式(而不是代码中实例化的内容),因此可以通过HTTP或作为嵌入式资源字符串加载 加载XAML工作正常,直到我尝试将一些样式定义分解到另一个文件中,然后XamlReader.Load()失败,并注意到:“属性AboutPageDo

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

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

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

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

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

这就是那个混蛋。。。如果简单地复制粘贴StackPanel代码(在运行时动态加载)并将其放入UserControl。。。事情进展顺利

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

考虑到源路径不正确,我尝试通过两个程序集将CommonStyles.xaml的副本放置在不同的位置。。。以及对pack://uri语法的实验。。。到目前为止,一切都没有用


我缺少什么?

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

当我在调用XamlReader.Load()时指定一个ParserContext时,我发现这对我来说是可行的


首先为什么要使用
XamlReader.Load
?如果您需要一个没有XAML的可重用控件,那么应该用C#硬写文档。这里也有同样的问题。奇怪的是,如果指定不可能成为解决方案的完整绝对路径,它就会起作用。因此,XamlReader能够解析对更多XAML文件的引用,但不能使用相对路径。
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 );
}