我有一个带有ListView控制器的wpf窗口和一堆项目。
<ListView Name="lvUsers" SelectionChanged="lvUsers_SelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
我可以将此ListView转换为List<T>
,以便我可以在XML文件中对其进行序列化吗?
我试过了:
foreach (ListViewItem item in lvUsers.SelectedItems)
{
foreach (ListViewItem.ListViewSubItem subItem in lvUsers.SubItems)
{
}
}
但是这段代码不起作用,因为ListViw不会包含SubItem属性。
答案 0 :(得分:0)
要序列化您的数据,您的数据必须是可序列化的。你在哪里以及如何定义它?最好的方法是定义ObservableCollection<YourClass>
并在ItemsSource
中将其用作ListView
。如果YourClass
是可序列化的,则可以从该数据集合中获取数据并对其进行序列化。
<Window
x:Class="WpfApp2.MainWindow"
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:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button Click="ButtonBase_OnClick">Serialize</Button>
<ListView ItemsSource="{Binding AllMyData}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
namespace WpfApp2
{
public partial class MainWindow : Window
{
public class YourClass
{
public string Name { get; set; }
public string Age { get; set; }
public string Mail { get; set; }
}
public ObservableCollection<YourClass> AllMyData { get; set; }
public MainWindow()
{
InitializeComponent();
AllMyData = new ObservableCollection<YourClass>();
for (var i = 0; i < 3; i++)
{
AllMyData.Add(new YourClass { Name = i.ToString() });
}
this.DataContext = this;
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(List<YourClass>));
var subReq = AllMyData.ToList();
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, subReq);
xml = sww.ToString(); // Your XML
Debugger.Break();
}
}
}
}
}