Display XML file into ListBox
I'm new to WPF/C# programming. I'm trying to display a xml file content into a listbox using this XAML code :
<Window x:Class="test.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">
<Window.Resources>
<XmlDataProvider x:Key="HostsData"
Source="/Hosts.xml"
XPath="Hosts/Host" />
</Window.Resources>
<Grid>
<ListBox Height="100" HorizontalAlignment="Left" Margin="98,70,0,0" Name="li开发者_Python百科stBox1"
VerticalAlignment="Top" Width="120" SelectionChanged="listBox1_SelectionChanged"
ItemsSource="{Binding Source={StaticResource HostsData}}"
DisplayMemberPath="HostName"/>
</Grid>
</Window>
And Hosts.xml contains :
<Hosts>
<Host>
<IP>1.1.1.1</IP>
<HostName>abc01</HostName>
</Host>
<Host>
<IP>2.2.2.2</IP>
<HostName>abc02</HostName>
</Host>
</Hosts>
I build successfully but when I run the app, the listbox is empty ! I've copied the Hosts.xml file everywhere but still nothing.
Any idea please ?
i tried like this.... just have a look
<Window x:Class="WpfApplication2.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window4" Height="300" Width="300">
<Window.Resources>
<XmlDataProvider x:Key="BookmarkData" XPath="Hosts/Host">
<x:XData>
<Hosts>
<Host>
<IP>1.1.1.1</IP>
<HostName>abc01</HostName>
</Host>
<Host>
<IP>2.2.2.2</IP>
<HostName>abc02</HostName>
</Host>
</Hosts>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<ListBox
Background="#999"
BorderThickness="2"
BorderBrush="White"
Margin="10"
DisplayMemberPath="HostName"
ItemsSource="{Binding Source={StaticResource BookmarkData}, XPath=/Hosts/Host}"
/>
</Grid>
i think you forgot to specify a Data Context.
DataContext="{Binding Source={StaticResource HostsData}}
either as a Grid xaml property, or Listbox.
And since the data comes from a XML provider, try to use the Xpath property tag
EDIT :
i found it more relevant to post a full example implementation, please ignore the Blend specific namespaces
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="Screen_2_1_Name"
mc:Ignorable="d"
x:Class="WpfPrototype1Screens.Screen_2_1"
Width="640" Height="480">
<UserControl.Resources>
<XmlDataProvider x:Key="uneDataSource" Source="http://www.lemonde.fr/rss/une.xml" d:IsDataSource="True"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource uneDataSource}}">
<ListBox Margin="80,88,64,112" Style="{DynamicResource ListBox-Sketch}" ItemsSource="{Binding XPath=/rss/channel/item/title}"/>
</Grid>
精彩评论