tags:

views:

262

answers:

1

I'm using XamlReader.Load() to load an external XAML file which may contain some images and other media.

I'm using ParserContext to set the baseUri, so if the paths inside the XAML file are correct, the media is loaded successfully.

// works
var pc = new ParserContext();
pc.BaseUri = new Uri(baseUri, UriKind.RelativeOrAbsolute);

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    return XamlReader.Load(stream, pc);

Is there a way for me to figure out which media files will fail to load? That is, if the XAML file contains an Image tag with the source set to a path that doesn't exist, can I tell at runtime that an image is not being displayed correctly? (Images will be the most common, but other controls like MediaElement might load external files too.)

I can think of a few possible approaches:

  • Parse the XAML file to find any filenames, and check each of them directly.
  • When displaying the resulting visual tree, look for some sort of RoutedEvent that would indicate a problem loading external files

Any tips?


Edit: I'm thinking the XamlReader stuff may be a distraction; I'm getting a valid visual tree, but it's the controls themselves that may have a problem when trying to load files that don't exist. Those are the errors I want to catch.

A: 

If you are linking your image via binding them to an background object, you will find errors with binding in WPF do not raise exceptions. Have a look at this blog article which may help get around this limitation.

The Media Element however, is simpler as it has an event (MediaFailed) which you can catch in order to determine if it has failed.

<MediaElement Source="filePath.wmv" MediaFailed="EventHandler"/>
John