0

我有类似于下面示例的 XML 数据,我正在尝试将其绑定到 ListView。我无法绑定元素名称,即示例中的汽车品牌。我从这篇文章Xaml Support for Local Name in XPath中发现 xaml 不支持 xpath 函数名称。因此,local-name() 不起作用。但是必须有办法做到这一点......

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
  <Window.Resources>
    <XmlDataProvider x:Key="DataSource">
      <x:XData>
        <Cars xmlns="">
          <Data>
            <Honda Year="2012"
                   Color="Red"
                   Model="Accord" />
            <Subuar Year="2008"
                    Color="Blue"
                    Model="Outback" />
            <Ford Year="2000"
                  Color="Black"
                  Model="Focus" />
          </Data>
        </Cars>
      </x:XData>
    </XmlDataProvider>
  </Window.Resources>
  <ListView ItemsSource="{Binding XPath=Cars/Data/*}"
            DataContext="{StaticResource DataSource}">
    <ListView.View>
      <GridView>
        <GridViewColumn DisplayMemberBinding="{Binding XPath=???}"
                        Header="Brand" />
        <GridViewColumn DisplayMemberBinding="{Binding XPath=@Year}"
                        Header="Year" />
        <GridViewColumn DisplayMemberBinding="{Binding XPath=@Color}"
                        Header="Color" />
        <GridViewColumn DisplayMemberBinding="{Binding XPath=@Model}"
                        Header="Model" />
      </GridView>
    </ListView.View>
  </ListView>
</Window>
4

2 回答 2

1

我认为您不能绑定到元素名称,需要“name()”或“local-name()”XPath 函数,但 Xaml 不支持它们。您可以解决它,请参阅此 URL:

XPath 中对 local-name() 的 XAML 支持

但这确实有效,并且不像 hack-ar 那样丑陋,只需要稍微不同的 XML 输入:

<Window.Resources>
    <XmlDataProvider x:Key="DataSource">
        <x:XData>
            <Cars xmlns="">
                <Data>
                    <Car Brand="Honda" Year="2012" Color="Red" Model="Accord"/>
                    <Car Brand="Subuaru" Year="2008" Color="Blue" Model="Outback"/>
                    <Car Brand="Ford" Year="2000" Color="Black" Model="Focus"/>
                </Data>
            </Cars>
        </x:XData>
    </XmlDataProvider>
</Window.Resources>
<ListView ItemsSource="{Binding XPath=Cars/Data/*}" DataContext="{StaticResource DataSource}">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding XPath=@Brand}" Header="Brand"/>
            <GridViewColumn DisplayMemberBinding="{Binding XPath=@Year}" Header="Year"/>
            <GridViewColumn DisplayMemberBinding="{Binding XPath=@Color}" Header="Color"/>
            <GridViewColumn DisplayMemberBinding="{Binding XPath=@Model}" Header="Model"/>
        </GridView>
    </ListView.View>
</ListView>
于 2012-11-30T03:02:54.447 回答
1

如果你使用正常Binding.Path的应该绑定到DataContext应该是一个对象的属性,XmlElement所以只是尝试{Binding Name}

于 2012-11-30T08:24:56.520 回答