【问题标题】:How to bind my xml data to a listbox?如何将我的 xml 数据绑定到列表框?
【发布时间】:2015-09-05 16:21:37
【问题描述】:

我想将我的数据从 xml 文件绑定到一个列表框,但我失败了。

这是我的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<Cams>
   <Cam>
     <Name>Name</Name>
     <Link>Link</Link>
     <Path>Path</Path>
   </Cam>
</Cams>

这里是我的 Xaml 文件的开头:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Properties="clr-namespace:CamManager.Properties" x:Name="MainForm" x:Class="CamManager.MainWindow"
    Title="CamManager" Height="190.69" Width="336.724" WindowStyle="ToolWindow" ResizeMode="NoResize" Background="White" BorderBrush="Black">
<Window.Resources>
    <XmlDataProvider x:Key="Data" Source="CamCollection.xml"/>
</Window.Resources>
<Grid>
    <TabControl HorizontalAlignment="Left" Height="322" VerticalAlignment="Top" Width="519">
        <TabItem Header="Collection">
            <Grid Background="#FFE5E5E5" Margin="0,0,185,153">
                <ListBox x:Name="Collection" HorizontalAlignment="Left" Height="124" VerticalAlignment="Top" Width="235" ItemsSource="{Binding Source={StaticResource Data}, XPath=/Cams/Cam/Name}"/>
                <Button x:Name="Launch" Content="Launch" HorizontalAlignment="Left" Margin="240,36,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.103,-0.084"/>
                <Button x:Name="Delete" Content="Delete" HorizontalAlignment="Left" Margin="240,61,0,0" VerticalAlignment="Top" Width="75"/>
            </Grid>
        </TabItem>

当我启动程序时,我的列表框保持空白,所以我希望有“名称”。

编辑:感谢您的解决方案,但这不是我的问题,我不知道为什么,但是当我指定源时,我必须指定我的 xml 的整个路径

Source="C:\Users...\CamCollection.xml" 如果你知道为什么?

【问题讨论】:

  • 如果您将XPath 中的CamCollection 更改为仅Cams,会发生什么情况?您的 xml 中没有 CamCollection
  • 是的,这是我的问题的原因,但不是全部

标签: c# xml wpf data-binding listbox


【解决方案1】:

解决方案1:

<XmlDataProvider x:Key="Data" Source="CamCollection.xml" XPath="Cams/Cam/Name"/>

解决方案2:

<ListBox x:Name="Collection" HorizontalAlignment="Left" Height="124" VerticalAlignment="Top" Width="235" ItemsSource="{Binding Source={StaticResource Data}, XPath=Cams/Cam/Name}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多