我是WPF / C#编程的新手。我正在尝试使用此XAML代码将xml文件内容显示到列表框中:
<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="listBox1"
VerticalAlignment="Top" Width="120" SelectionChanged="listBox1_SelectionChanged"
ItemsSource="{Binding Source={StaticResource HostsData}}"
DisplayMemberPath="HostName"/>
</Grid>
</Window>
Hosts.xml包含:
<Hosts>
<Host>
<IP>1.1.1.1</IP>
<HostName>abc01</HostName>
</Host>
<Host>
<IP>2.2.2.2</IP>
<HostName>abc02</HostName>
</Host>
</Hosts>
我成功构建但是当我运行应用程序时,列表框是空的!我已经在任何地方复制了Hosts.xml文件,但仍然没有。
请问好吗?
答案 0 :(得分:0)
我认为您忘记指定数据上下文。
DataContext="{Binding Source={StaticResource HostsData}}
作为Grid xaml属性或Listbox。
由于数据来自XML提供程序,请尝试使用Xpath属性标记
编辑:
我发现发布完整的示例实现更相关,请忽略Blend特定的命名空间
<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>
答案 1 :(得分:0)
我试过这样......只是看看
<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>