2012-11-30 47 views
0

我有類似於下面示例的XML數據,我正在嘗試將它綁定到ListView。我在綁定元素名稱時遇到了困難,這是該示例中汽車的品牌。我從這篇文章Xaml Support for Local Name in XPath中發現xaml不支持xpath函數名稱。因此,local-name()不起作用。但是,必須是一個辦法做到這一點...如何將xml元素名稱綁定到WPF XAML文件中的ListView列

<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 [email protected]}" 
         Header="Year" /> 
     <GridViewColumn DisplayMemberBinding="{Binding [email protected]}" 
         Header="Color" /> 
     <GridViewColumn DisplayMemberBinding="{Binding [email protected]}" 
         Header="Model" /> 
     </GridView> 
    </ListView.View> 
    </ListView> 
</Window> 
+0

由於它是單向綁定,我爲它寫了一個轉換器。 –

回答

1

如果使用正常的Binding.Path則應該綁定到DataContext對象的屬性,該對象應該是XmlElement,因此只需嘗試{Binding Name}即可。

+0

這真是太簡單了......謝謝! –

1

我不認爲你可以綁定到一個元素的名稱,是將需要「名稱()」或「本地名()」 XPath函數,但它們在Xaml中不受支持。你可以解決它,請參閱本網址:

XAML support for local-name() in XPath

但這並工作,而不是作爲一個黑客-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 [email protected]}" Header="Brand"/> 
      <GridViewColumn DisplayMemberBinding="{Binding [email protected]}" Header="Year"/> 
      <GridViewColumn DisplayMemberBinding="{Binding [email protected]}" Header="Color"/> 
      <GridViewColumn DisplayMemberBinding="{Binding [email protected]}" Header="Model"/> 
     </GridView> 
    </ListView.View> 
</ListView> 
+0

數據來自服務提供商,我無法控制其格式。 –

相關問題