tags:

views:

21

answers:

1

Sorry for this, I've just started programming with wpf. I can't seem to figure out why the following xaml displays "System.Xml.XmlElement" instead of the actual xml node content. This is displayed 5 times in the listbox whenever I run it. Not sure where I'm going wrong...

<Window x:Class="TestBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <XmlDataProvider x:Key="myXmlSource" XPath="/root">
            <x:XData>
                <root xmlns="">
                    <name>Steve</name>
                    <name>Arthur</name>
                    <name>Sidney</name>
                    <name>Billy</name>
                    <name>Steven</name>
                </root>
            </x:XData>
        </XmlDataProvider>
        <DataTemplate x:Key="shmooga">
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox ItemTemplate="{StaticResource shmooga}"
                 ItemsSource="{Binding Source={StaticResource myXmlSource}, XPath=name}">
        </ListBox>
    </Grid>
</Window>

Any help would be very much appreciated. Thanks!

A: 

Your ItemsSource Binding is returning the collection of 'name' elements. These are of type XmlElement. This is done because it allows bindings to get at other properties of the XmlElement, but means that if you textually display the result of the binding then you get System.Xml.XmlElement rather than the textual content.

To get the textual content, add an additional XPath to your ItemTemplate binding to specify that the TextBlock.Text property should bind specifically to the text of the element, not the element object itself:

<DataTemplate x:Key="shmooga">
  <TextBlock Text="{Binding XPath=text()}"/>  <!-- Note XPath on Binding -->
</DataTemplate>
itowlson
That's Great! Thanks! I was really stumped on this.
Andrew