2011-12-02 219 views
1

任何人都可以告訴爲什麼這不起作用。 這非常簡單,但啓動它時ListBox是空的。後面的代碼只包含InitializeComponent()。綁定列表框到XmlDataProvider

希望有人有一個想法......

<Window x:Class="DasDataGrid.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    Title="MainWindow" Height="350" Width="700"> 

    <Window.Resources> 
     <XmlDataProvider x:Key="Maschinen" XPath="/machines"> 
      <x:XData> 
       <machines> 
        <machine name="alte Maschine"/> 
        <machine name="neue Maschine"/> 
       </machines> 
      </x:XData> 
     </XmlDataProvider> 
    </Window.Resources> 
    <ListBox ItemsSource="{Binding Source={StaticResource Maschinen},XPath=machine/@name}" 
       IsSynchronizedWithCurrentItem="True" 
       SelectedIndex="1"> 
    </ListBox> 
</Window> 

@ H.B。 這是我測試的代碼。啓動它時,ListBox仍然是空的。我不知道什麼是錯的。

<Window x:Class="WpfApplication1.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"> 
<StackPanel> 
    <StackPanel.Resources> 
     <XmlDataProvider x:Key="Maschinen"> 
     <x:XData> 
      <machines xmlns=""> 
       <machine name="alte Maschine"/> 
       <machine name="neue Maschine"/> 
      </machines> 
     </x:XData> 
     </XmlDataProvider> 
    </StackPanel.Resources> 

    <ListBox ItemsSource="{Binding Source={StaticResource Maschinen}, XPath=machine}" 
     IsSynchronizedWithCurrentItem="True" DisplayMemberPath="@name" 
     SelectedIndex="1"> 
    </ListBox> 

</StackPanel> 
</Window>  

回答

0

您需要設置xmlns設置爲空字符串:

<x:XData> 
    <machines xmlns=""> 
     <machine name="alte Maschine"/> 
     <machine name="neue Maschine"/> 
    </machines> 
</x:XData> 

MSDN

XML數據的根節點有設置XML命名空間的xmlns屬性爲一個空字符串。這是將XPath查詢應用於XAML頁面內聯的數據島的要求。在這種內聯情況下,XAML以及數據島繼承System.Windows命名空間。因此,您需要將命名空間設置爲空以防止XPath查詢受到System.Windows命名空間的限制,從而導致查詢錯誤。


,你可能想正是如此綁定(即使它沒有在結果方面的差異):

<ListBox ItemsSource="{Binding Source={StaticResource Maschinen}, XPath=machine}" 
      IsSynchronizedWithCurrentItem="True" DisplayMemberPath="@name" 
      SelectedIndex="1"> 
</ListBox> 
+0

謝謝。我測試了你的代碼,但它不起作用。列表框仍然是空的。有任何想法嗎? – user1078325

+0

我測試過這個東西,也許你做了一些不同的事情?你可以暫時將你編輯的代碼附加到問題上嗎? –

+1

我發現我做錯了什麼:XPath =/machines/machine 然後,它的工作原理! 謝謝! – user1078325