将XML文件绑定到ListBox后,项目不会显示

问题描述 投票:1回答:1

我想将XML文件绑定到ListBox。问题是ListBox中的项目在将其绑定到XML文件后不会显示。

我已将ListBox中的ItemsSource设置为StaticResource但它不起作用,它不会显示在Visual Studio的Designer中或应用程序本身中。

这是XAML代码:

<Window x:Class="StudyNotes.ModifySubjectListWindow"
        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"
        xmlns:local="clr-namespace:StudyNotes"
        mc:Ignorable="d"
        Title="" Height="150" Width="300" ResizeMode="NoResize">
    <Grid>
        <Grid.Resources>
            <XmlDataProvider x:Key="SubjectData" Source="SubjectList.xml" XPath="/Subjects/Subject"/>
        </Grid.Resources>
        <DockPanel Margin="10">
            <StackPanel DockPanel.Dock="Right" Margin="10,0,0,0">
                <Button Name="AddSubjectButton" Margin="0,0,0,5">Add</Button>
                <Button Name="DeleteSubjectButton">Delete</Button>
            </StackPanel>
            <ListBox x:Name="SubjectList" ItemsSource="{Binding Source={StaticResource SubjectData}, XPath=/Subjects/Subject}"></ListBox>
        </DockPanel>
    </Grid>
</Window>

这是XML文档:

<?xml version="1.0" encoding="utf-8" ?>
<Subjects>
  <Subject Name="Subject1"/>
  <Subject Name="Subject2"/>
  <Subject Name="Subject3"/>
  <Subject Name="Subject4"/>
</Subjects>

我预计这会工作和出现,但肯定有一些我不知道的错误。

c# xml wpf binding listbox
1个回答
1
投票

有几个项目:

首先,确保您的'SubjectList.xml'文件的Build Action属性设置为'Content'。

其次,从ListBox的ItemsSource中删除“XPath”内容,这会导致一些麻烦。你只需要ItemsSource="{Binding Source={StaticResource SubjectData}}"

第三,这是最重要的,你的XML文件设置得不是很正确。完成上述两项更改后,将ListBox更改为DataGrid以进行快速测试,它将突出显示XML文件的问题:

enter image description here

在此屏幕截图中很难看到,但请查看“值”列。它是空的。您的XML文件已设置在您的数据存储在“属性”中,特别是“名称”属性,如您在“OuterXML”列中查看的那样。默认情况下,XMlDataProvider在XML文件中抓取Values。你没有任何这些。

存储XML数据的更好方法可能是:

<Subjects>
  <Subject>Subject1</Subject>
  <Subject>Subject2</Subject>
  <Subject>Subject3</Subject>
  <Subject>Subject4</Subject>
</Subjects>

如果你这样做,你会得到预期的结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.