XML序列化保存数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;
namespace TestWPFMsgItems
{
/// <summary>
/// Interaction logic for MsgListPanel.xaml
/// </summary>
public partial class MsgListPanel : UserControl
{
public MsgListPanel()
{
InitializeComponent();
msgFile = System.IO.Path.Combine("" + AppDomain.CurrentDomain.BaseDirectory, "mgs.d");
// addTestData();
loadMsgItems();
dataGridMsgList.DataContext = dataGridMsgList.ItemsSource = list;
}
public List<MsgItem> list = new List<MsgItem>();
private string msgFile = "";
private void btnDel_Click(object sender, RoutedEventArgs e)
{
var m = (sender as Button).DataContext as MsgItem;
list.Remove(m);
dataGridMsgList.ItemsSource = null;
dataGridMsgList.ItemsSource = list;
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Save();
}
void loadMsgItems()
{
dataGridMsgList.ItemsSource = null;
list = (List<MsgItem>)LoadFromXml(msgFile, list.GetType());
dataGridMsgList.ItemsSource = list;
}
object LoadFromXml(string filePath, Type type)
{
object result = null;
if (File.Exists(filePath))
{
using (StreamReader reader = new StreamReader(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
result = xmlSerializer.Deserialize(reader);
}
}
return result;
}
void SaveToXml(string filePath, object sourceObj)
{
if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(sourceObj.GetType());
XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
nameSpace.Add("", ""); //not ot output the default namespace
xmlSerializer.Serialize(writer, sourceObj, nameSpace);
}
}
}
void addTestData()
{
list = new List<MsgItem>();
for (int i = 1; i <= 2; i++)
{
list.Add(new MsgItem() { Age = 12, msg = "wgstrrrrrrrrrrrrrrrcd" });
list.Add(new MsgItem() { Age = 12, msg = "wgscd" });
list.Add(new MsgItem() { Age = 12, msg = "wgscd" });
}
}
public void Save()
{
SaveToXml(msgFile, list);
}
}
//数据类
public class MsgItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private String _msg = "hello !!";
private int _age = 24;
public String msg
{
set
{
_msg = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("msg"));
}
}
get
{
return _msg;
}
}
public int Age
{
set
{
_age = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));//对Age进行监听
}
}
get
{
return _age;
}
}
}
}
界面UI 代码:
<UserControl x:Class="TestWPFMsgItems.MsgListPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="322" d:DesignWidth="700">
<Grid>
<DataGrid Name="dataGridMsgList" ItemsSource="{Binding}" AutoGenerateColumns="False" GridLinesVisibility="Horizontal" HorizontalGridLinesBrush="#FFEF7D7D" Margin="0,70,0,0" SelectionUnit="Cell">
<DataGrid.Columns>
<DataGridTextColumn Width="342" Header="ATH" Binding="{Binding msg}"/>
<DataGridTemplateColumn Header="action" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Click="btnDel_Click" Tag="777" Content="X delete" VerticalAlignment="Top" Cursor="Hand">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button Margin="5" Content="测试LinkButton" Width="123" VerticalAlignment="Top" Cursor="Hand">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<Button Content="save" Height="23" HorizontalAlignment="Left" Margin="31,12,0,0" Name="btnClose" Click="btnClose_Click" VerticalAlignment="Top" Width="75" />
</Grid>
</UserControl>