我有一个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; }
}
这是Collection类文件
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}" />
现在我想只在列表框中显示名称,并且在添加新记录时应自动更新列表框。当我执行abov提到的代码时,我在xaml文件中得到一个异常,例如“在System.Windows.StaticResourceExtension上提供值”
答案 0 :(得分: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>