我是WPF/C#編程的新手。我試圖用這個XAML代碼顯示一個XML文件內容到一個列表框:將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文件,但仍然沒有任何東西。
有什麼想法嗎?
我只是測試相同的代碼不具有的SelectionChanged屬性和列表框顯示2個元素。你是什麼意思「我已經複製Hosts.xml文件到處」? – 2011-04-09 20:44:16
當我將XML文件添加到項目中時,它工作正常,列出了內容。但這不是我想要的,我的意思是我想使用外部XML文件 – 2011-04-09 21:27:15
外部XML文件存儲在哪裏?您只需爲XmlDataProvider提供一個有效的源代碼。這可能是例如本地文件或URL的路徑。 – 2011-04-09 21:43:37