XmlDataProvider的转换器问题

时间:2010-04-16 19:28:08

标签: wpf xml xaml

对不起,我刚开始用wpf编程。我似乎无法弄清楚为什么以下xaml显示“System.Xml.XmlElement”而不是实际的xml节点内容。每当我运行它时,它会在列表框中显示5次。不知道我哪里错了......

<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>

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您的ItemsSource Binding返回'name'元素的集合。这些是XmlElement类型。这样做是因为它允许绑定获取XmlElement的其他属性,但意味着如果以文本方式显示绑定的结果,那么您将获得System.Xml.XmlElement而不是文本内容。

要获取文本内容,请在ItemTemplate绑定中添加一个额外的XPath,以指定TextBlock.Text属性应该专门绑定到元素的文本,而不是元素对象本身:

<DataTemplate x:Key="shmooga">
  <TextBlock Text="{Binding XPath=text()}"/>  <!-- Note XPath on Binding -->
</DataTemplate>