1

谁能告诉为什么这不起作用。这真的很简单,但是启动时 ListBox 是空的。后面的代码只包含 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>

@HB 这是我测试的代码。启动它时,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>    
4

1 回答 1

0

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

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

MSDN

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


而且您可能希望如此绑定(即使它在结果方面没有区别):

<ListBox ItemsSource="{Binding Source={StaticResource Maschinen}, XPath=machine}"
          IsSynchronizedWithCurrentItem="True" DisplayMemberPath="@name"
          SelectedIndex="1">
</ListBox>
于 2011-12-02T22:41:09.790 回答