Wpf 将ListBox绑定到XmlDataProvider

Wpf 将ListBox绑定到XmlDataProvider,wpf,xaml,data-binding,listbox,xmldataprovider,Wpf,Xaml,Data Binding,Listbox,Xmldataprovider,有人能告诉我为什么这不起作用吗。 它非常简单,但启动时列表框是空的。隐藏的代码只包含InitializeComponent(),不包含其他内容 希望有人有个主意 <Window x:Class="DasDataGrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xa

有人能告诉我为什么这不起作用吗。 它非常简单,但启动时列表框是空的。隐藏的代码只包含InitializeComponent(),不包含其他内容

希望有人有个主意

<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。 这是我测试的代码。启动时,列表框仍然为空。我不知道怎么了

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

您需要将xmlns设置为空字符串:

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

:

XML数据的根节点具有一个xmlns属性,该属性将XML名称空间设置为空字符串。这是将XPath查询应用于XAML页面中内联的数据岛的要求。在这种内联情况下,XAML和数据岛继承System.Windows命名空间。因此,您需要将名称空间设置为空,以防止System.Windows名称空间限定XPath查询,这将误导查询


您可能希望这样绑定(即使它在结果方面没有什么区别):



谢谢。我测试了你的代码,但不起作用。列表框仍然是空的。有什么想法吗?我测试了这个东西,也许你做了一些不同的事情?您可以暂时将您编辑的代码附加到问题中吗?我发现我做错了什么:XPath=/machines/machine然后它就可以工作了!谢谢
<ListBox ItemsSource="{Binding Source={StaticResource Maschinen}, XPath=machine}"
          IsSynchronizedWithCurrentItem="True" DisplayMemberPath="@name"
          SelectedIndex="1">
</ListBox>