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>

  

WPF XML序列化保存数据 支持Datagrid 显示/编辑/添加/删除数据的更多相关文章

  1. 《ASP.NET1200例》在DataList里编辑和删除数据

    学习内容:如何创建一个支持编辑和删除数据的DataList.增加编辑和删除功能需要在DataList的ItemTemplate和EditItemTemplate里增加合适的控件,创建对应的事件处理,读 ...

  2. SQL语句的使用,SELECT - 从数据库表中获取数据 UPDATE - 更新数据库表中的数据 DELETE - 从数据库表中删除数据 INSERT INTO - 向数据库表中插入数据

    SQL DML 和 DDL 可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL). SQL (结构化查询语言)是用于执行查询的语法. 但是 SQL 语言也包含用于更新. ...

  3. 数据表格 - DataGrid - 行编辑

    行编辑一般用于单行数据的增删改,如果不用行编辑实现的话,对于表单数据量不大的情况,可以使用弹窗(Dialog),如果数据量比较大,也就是需要操作的数据比较多的时候,可以新开一个tab页. 新增/编辑 ...

  4. easyui datagrid 批量编辑和提交数据

    easyui datagrid 行编辑和提交方,废话就不多说了,直接上代码 <div style="margin: 5px;"> <table id=" ...

  5. 使用Bootstrap + Vue.js实现 添加删除数据

    界面首先需要引入bootstrap的css和bootstrap的js文件,还有vue.js和jQuery.js才可以看见效果. 这里提供bootstrap的在线文件给大家引用: <!-- 最新版 ...

  6. WPF下的Richtextbox中实现表格合并,添加删除行列等功能

    .Net中已有现在的方法实现这些功能,不过可能是由于未完善,未把方法公开出来.只能用反射的方法去调用它. 详细信息可以查看.Net Framework 的源代码 http://referencesou ...

  7. 【Excle数据透透视表】如何删除数据透视表

    选中区域A4:C17,在键盘上按DELETE键删除,结果提示: 那么如何删除呢? 解决方案 选中整个数透视表,再删除 具体操作: 选中整个数据透视表→DELETE 注意:删除之后,源数据不会受到影响

  8. Windowsphone 之xml序列化和反序列化的应用(WebService解析返回的数据DataSet )

    关于Xml的序列化和反序列化: 可以看这篇文章,http://www.cnblogs.com/Windows-phone/p/3243575.html WebService解析返回的数据DataSet ...

  9. c# 使用 静态类+xml序列化 保存配置文件

    namespace TVCorrectionDataProcess{    [XmlRoot(ElementName = "Config")]    public class Co ...

随机推荐

  1. js 匿名函数立即执行问题

    js立即执行函数写法理解 这篇真的写得很清楚了,不光括号可以将函数声明转换成函数表达式然后立即执行,!,+,-,=也都可以转换,但是可能会带来意外的结果,因此一般都用括号实现. 还有关于for (va ...

  2. apt-get update 系列作用

    sudo apt-get update 更新源 sudo apt-get upgrade 更新已安装的包 sudo apt-get dist-upgrade 升级系统 下面摘自知乎用户回答: apt- ...

  3. 在ActiveReports页面报表中显示Google地图

    有些报表需求中需要我们显示国家.城市等地址信息,在报表中添加地图信息会让报表给最终用户代码更多有效信息. 在报表中可以将地图作为图片添加进来,当一个图片显示在报表中时,该图片必须存放到本地计算机或者服 ...

  4. MySQL——索引实现原理

    在MySQL中,索引属于存储引擎级别的概念,不同存储引擎对索引的实现方式是不同的,本文主要讨论MyISAM和InnoDB两个存储引擎的索引实现方式. MyISAM索引实现 MyISAM引擎使用B+Tr ...

  5. NodeJS自定义模块

    //1.创建测试模块js文件(我这里命名为test.js) //2.添加测试方法 function test(){ console.log('Test Success!'); } //3.公开该方法到 ...

  6. 纯Css实现Div高度根据自适应宽度(百分比)调整

    在如今响应式布局的要求下,很多能自动调整尺寸的元素能够做到高宽自适应,如img,通过{width:50%;height:auto;}实现图片高度跟随宽度比例调整. 然而,用的最多的标签一哥Div却不能 ...

  7. RHEL7.3安装python3.6.1

    RHEL7.3 install python3.6.1 steps 1. download Python-3.6.1.tgz2. tar -zxvf Python-3.6.1.tgz3. yum in ...

  8. 【转】Linxu学习---top实践

    [原文]https://www.toutiao.com/i6591053058258502147/ 在实际开发中,有时候会收到一些服务的监控报警,比如CPU飙高,内存飙高等,这个时候,我们会登录到服务 ...

  9. 再谈全局网HBase八大应用场景

    摘要: HBase可以说是一个数据库,也可以说是一个存储.拥有双重属性的HBase天生就具备广阔的应用场景.在2.0中,引入了OffHeap降低了延迟,可以满足在线的需求.引入MOB,可以存储10M左 ...

  10. 0基础的人如何入门 Python ?Python难么?

    人生苦短,我用Python,为啥这么说,因为我们自动化测试有金句:学完Python,便可上天 ~ 废话不多说,相信很多人都听过之前的Python进入小学课本.Python进入浙江省高考等新闻,有这么多 ...