Successfully referencing ResourceDictionary in file being loaded by XamlReader.Load()

1k Views Asked by At

I am building a common WP7 assembly which will display common help/about information for my apps, each app assembly will specify a pair of StackPanels which have some of the app specific information (well call em Legal.xaml and WhatsNew.xaml).

Ideally these app specific XAML files should be in a plaintext form (vs something that is instantiated in code) so loadable via HTTP or as an embedded resource string.

Loading the XAML works fine, until I try to break out some of the style definitions into another file, then XamlReader.Load() fails with a note that: “Attribute AboutPageDocs/CommonStyles.xaml value is out of range. [Line: 43 Position: 45]”

That error would happen when loading Legal.xaml, which when we look around like 43 we find where I am attempting to load the ResourceDictionary that now contains the custom styles:

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

Here is the bugger... if simply copy & paste the StackPanel code (which is being loaded dynamically at runtime) and drop it into a UserControl... things work fine.

Short of having to define my styles inline in both Legal.xaml & WhatsNew.xaml... is there any way to have XamlReader.Load() property lookup CommonStyles.xaml?

On the thought that the Source path was not correct, I have tried placing copies of CommonStyles.xaml in various locations through both assemblies... as well as experimented with the pack:// uri syntax... all to no avail thus far.

What am I missing?

1

There are 1 best solutions below

0
On

As I realized that XamlReader is able to resolve referenced XAML files when they are specified as absolute paths, I looked for a possibility to specify an own context.

I found this working for me, when I specify a ParserContext when calling XamlReader.Load()

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