【问题标题】:Successfully referencing ResourceDictionary in file being loaded by XamlReader.Load()在 XamlReader.Load() 加载的文件中成功引用 ResourceDictionary
【发布时间】:2012-01-13 17:14:29
【问题描述】:

我正在构建一个通用 WP7 程序集,它将显示我的应用程序的常见帮助/关于信息,每个应用程序程序集将指定一对 StackPanels,其中包含一些应用程序特定信息(以及调用 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 语法...全部为否到目前为止有效。

我错过了什么?

【问题讨论】:

  • 你为什么首先使用XamlReader.Load?如果你需要一个没有 XAML 的可重用控件,你应该用 C# 硬写文档。
  • 这里有同样的问题。奇怪的是,如果指定不能成为解决方案的完整绝对路径,它会起作用。所以 XamlReader 能够解析对其他 XAML 文件的引用,但不能解析相对路径。

标签: xaml windows-phone-7 resourcedictionary xamlreader


【解决方案1】:

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

当我在调用 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 );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2017-03-30
    • 2012-02-07
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多