0

我有一个 Xml 文件,它有一些元素,我想在列表框中只显示一个,并且在添加新记录时应该更新列表框。更新应该是动态的。我尝试了绑定,但没有帮助。

这是我的 XML 文件

<empList>
<Information>
  <Name>Jack</Name>
  <Destination>AA</Destination>
  <EmployeeID>AA</EmployeeID>
</Information>
<Information>
  <Name>David</Name>
  <Destination>BB</Destination>
  <EmployeeID>BB</EmployeeID>
</Information>
<Information>
  <Name>Adam</Name>
  <Destination>wdwad</Destination>
  <EmployeeID>dwad</EmployeeID>
</Information></empList>

这是类文件

public class Information
{

     public string Name{ get; set; }

     public string Destination{ get; set; }

     public string EmployeeID{ get; set; }

    }

这是集合类文件

public class Collection
{

    public List<Information> empList = new List<Information>();
}

这是 .cs 文件

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
            XmlSerializer xs = new XmlSerializer(typeof(Collection));
            FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
            Collection coll = (Collection)xs.Deserialize(read);
            listBox1.ItemsSource = coll.empList;


    }

这是 XAML 文件

 <ListBox Height="251" HorizontalAlignment="Left" Margin="334,22,0,0" Name="listBox1" VerticalAlignment="Top" Width="170" 
DataContext="{Binding {StaticResource Data}, XPath=empList/Information}"
ItemsSource="{Binding XPath=Information/@Name}" />

现在我只想在列表框上显示名称,并且在添加新记录时列表框应该自动更新。当我执行上面提到的代码时,我在 xaml 文件中出现异常,例如“在 'System.Windows.StaticResourceExtension 上提供值”

4

1 回答 1

1

您可以在 WPF 中绑定属性,并且 XML 文件是信息的集合,因此您需要在开始时添加 Collection 标签试试这个:

XAML:

<Grid >
        <ListBox Height="251" HorizontalAlignment="Left" Margin="334,22,0,0" Name="listBox1" VerticalAlignment="Top" Width="170" 
        DisplayMemberPath="Name" />
</Grid>

收藏:

public class Collection 
    {
        public ObservableCollection<Information> empList { get; set; }

        public Collection()
        {
            empList = new ObservableCollection<Information>();
        }
    }

XML反序列化:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            XmlSerializer xs = new XmlSerializer(typeof(Collection));
            FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
            Collection coll = (Collection)xs.Deserialize(read);
            listBox1.ItemsSource = coll.empList;
        }

XML 文件:

<?xml version="1.0" encoding="utf-8" ?>
<Collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <empList>
    <Information>
      <Name>Jack</Name>
      <Destination>AA</Destination>
      <EmployeeID>AA</EmployeeID>
    </Information>
    <Information>
      <Name>David</Name>
      <Destination>BB</Destination>
      <EmployeeID>BB</EmployeeID>
    </Information>
    <Information>
      <Name>Adam</Name>
      <Destination>wdwad</Destination>
      <EmployeeID>dwad</EmployeeID>
    </Information>
  </empList>
</Collection>
于 2013-09-06T06:57:20.733 回答