【问题标题】:Binding ListBox to XmlDataProvider将 ListBox 绑定到 XmlDataProvider
【发布时间】:2012-01-11 21:50:25
【问题描述】:

谁能说出为什么这不起作用。 这真的很简单,但是启动时 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>

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

【问题讨论】:

    标签: wpf xaml data-binding listbox xmldataprovider


    【解决方案1】:

    您需要将 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>
    

    【讨论】:

    • 谢谢。我测试了你的代码,但它不起作用。 ListBox 仍然是空的。有什么想法吗?
    • 我测试了这个东西,也许你做了一些不同的事情?您能否暂时将您编辑的代码附加到问题中?
    • 我发现我做错了什么:XPath=/machines/machine 然后它工作了!谢谢!
    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2019-12-05
    相关资源
    最近更新 更多