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. <Android 应用 之路> 干货集中营 ~ GankIOClient

    简介 利用干货集中营 , daimajia和他的小伙伴给我们开发者带来的福利开发的一个干货集中营客户端,主要功能在阅读干货上. Github地址: https://github.com/onlylov ...

  2. 关于TCP/IOCP构架中出现的假死连接解决方案

    如果在2台不同的公网机器,对TCP的c/s做过详细的压力测试,那么很不幸,会有很多人发现自己的server端会出现大量的假死连接. 假死连接具体表现如下: 1.在s端机器上,会有一些处于TCP_EST ...

  3. JavaScript Math对象方法

    console.log(Math.abs(123));//绝对值 console.log(Math.ceil(123.3));//向上舍入 console.log(Math.floor(123));/ ...

  4. Android Monkey的使用

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/71750907 本文出自[赵彦军的博客] 什么是 Monkey Monkey 是一个 ...

  5. BaseDAL最牛数据层基类2

    using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using Syste ...

  6. Ubuntu 18.04 Server 设置静态IP

    一.背景 Netplan是Ubuntu 17.10中引入的一种新的命令行网络配置实用程序,用于在Ubuntu系统中轻松管理和配置网络设置.它允许您使用YAML抽象来配置网络接口.它可与NetworkM ...

  7. 控制台中寄宿WCF服务

    一.首先创建一个类库,用来定义WCF服务 修改服务代码定义,具体代码如下 // 注意: 使用"重构"菜单上的"重命名"命令,可以同时更改代码和配置文件中的接口名 ...

  8. SQL Server 合并复制如何把备份的发布端或订阅端BAK文件还原为数据库

    SQL Server的合并复制,是可以备份发布端和订阅端数据库为BAK文件的,但是问题是合并复制在数据库中自动创建的系统表.触发器.表中的RowGuid列等也会被一起备份. 这里我们举个例子,下面图中 ...

  9. Java 设计模式笔记

    0. 说明 转载 & 参考大部分内容 JAVA设计模式总结之23种设计模式 1. 什么是设计模式 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设 ...

  10. tp5 migrate数据库迁移工具

    tp5相对与tp3.2有很大的不同 migrate是其中一点,通过migrate程序员可以在php代码中创建数据库修改回滚等操作 首先下载migrate扩展,命令行到当前项目目录下执行 compose ...