I have XML data similar to the example below and I am trying to bind it to a ListView. I am having trouble binding the element name, which is the brand of the car in the example. I have found out from this post Xaml Support for Local Name in XPath that xaml doesn't support xpath function names. Therefore, local-name() doesn't work. But there got to be a way to do this...
<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>
I don't think you can bind to an element name, is would require the "name()" or "local-name()" XPath functions, but they aren't supported in Xaml. You can work around it, see this URL:
XAML support for local-name() in XPath
But this does work and isn't as ugly as a hack-ar, just requires a slightly different XML input:
<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>
如果你使用普通的Binding.Path
应该绑定到DataContext
对象的属性,该对象应该是一个XmlElement
所以只需尝试{Binding Name}
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.