wpf xml 转化对象_[WPF]xml序列化以及反序列化数据

代码

XML序列化工具类

public static class XMLHelper

{

///

/// 将对象序列化为指定的文件名

///

///

///

///

///

public static bool SaveObjAsXml(T obj,string fileName)

{

var dir = Application.StartupPath;

try

{

FileStream fs = new FileStream(dir+"/"+fileName, FileMode.Create);

XmlSerializer xs = new XmlSerializer(typeof(T));

xs.Serialize(fs, obj);

fs.Close();

return true;

}

catch (Exception e)

{

Console.WriteLine(e);

throw;

}

}

///

/// 将xml文件进行反序列化

///

///

///

///

public static T DecodeXML(string fileName)

{

var dir = Application.StartupPath;

fileName = dir + "/" + fileName;

try

{

if (File.Exists(fileName)==false)

return default(T);

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

XmlSerializer xs = new XmlSerializer(typeof(T));

T obj = (T)xs.Deserialize(fs);

return obj;

}catch(Exception ex)

{

Console.WriteLine(ex.Message);

throw;

}

}

}

对应的窗体数据类可以定义为:

[XmlRoot]

public class WindowsData:PropertyChangedBase

{

[XmlElement("WindowsIndex")]

///

/// Windows窗体索引

///

public int WindowsIndex{get;set; }

[XmlElement("FontSize")]

private double fontSize=14;

///

/// 窗体字体

///

public double FontSize

{

get { return fontSize;}

set

{

fontSize=value;

OnPropertyChanged("FontSize");

}

}

private Point startUpPosition;

[XmlElement("LeftTopWinPosition")]

public Point StartUpPosition

{

get { return startUpPosition; }

set

{

startUpPosition = value;

OnPropertyChanged("StartUpPosition");

}

}

///

/// 窗体宽度

///

private int windowsWidth;

public int WindowsWidth

{

get { return windowsWidth; }

set { windowsWidth = value;OnPropertyChanged("WindowsWidth"); }

}

private int windowsHeight;

public int WindowsHeight

{

get { return windowsHeight; }

set

{

windowsHeight = value;

OnPropertyChanged("WindowsHeight");

}

}

private string richTextBoxContent;

[XmlElement("UserInputNotes")]

public string RichTextBoxContent

{

get { return richTextBoxContent; }

set

{

richTextBoxContent = value;

OnPropertyChanged("RichTextBoxContent");

}

}

public WindowsData()

{

// MessageBox.Show("新的窗体数据加载了");

WindowsIndex = GenerateWindowsIndex.Generate();

WindowsWidth = 350;

WindowsHeight = 450;

double screenHeight = SystemParameters.FullPrimaryScreenHeight;

double screenWidth = SystemParameters.FullPrimaryScreenWidth;

StartUpPosition =new Point((screenWidth - WindowsWidth)/2,(screenHeight - WindowsHeight)/2);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值