Binding ListBox to XmlDataProvider

3.2k Views Asked by At

Can anyone tell why this isn't working. It is really simple but the ListBox is empty when starting it. The code behind contains only InitializeComponent() nothing else.

Hopefully someone has an idea ...

<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. Here is the code I tested. When starting it the ListBox ist still empty. I don't know whats wrong.

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

There are 1 best solutions below

3
On

You need to set the xmlns to be an empty string:

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

MSDN:

The root node of the XML data has an xmlns attribute that sets the XML namespace to an empty string. This is a requirement for applying XPath queries to a data island that is inline within the XAML page. In this inline case, the XAML, and thus the data island, inherits the System.Windows namespace. Because of this, you need to set the namespace blank to keep XPath queries from being qualified by the System.Windows namespace, which would misdirect the queries.


And you might want to bind thusly (even though it does not make a difference in terms of results):

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