« How much personal information do you provide ....? | Main | More fun with Value Converters »

Remember the Power of the Path, young WPF'er

Binding's in WPF can make quick work of getting values from object properties.

I've created a class with a property:

    public XmlElement SelectedVideo
    {
      get { return _selectedVideo; }
    }

This Property is  of Type XmlElement. The XmlElement it binds to typically is structured like this:

<Video title="Anonymous Methods" source="Data\anonmethods.wmv" 
timecode="00:01:00" />

With a tiny bit of binding magic, I can easily fetch the title from the element and display it within a textblock:

<TextBlock Text="{Binding Path=SelectedVideo.Attributes[title].Value, Mode=OneWay}"

Since this is a read-only XmlElement, I've set the Mode to be OneWay (as it can't be updated via the TextBlock). Since the element may change, I need to use OneWay binding. OneTime wouldn't work as the SelectedVideo element may change.

The slick part is that the binding syntax allows me to use the indexer on the Attributes object. The only odd thing is that it doesn't need any quotation marks or delimiters.

I'm not using XPath bindings here because I'm not binding directly to an Xml Data Provider in my application (not always at least).

Help support my web site by searching and buying through Amazon.com (in assocation with Amazon.com).