gpt4 book ai didi

c# - 将 WPF 中的对象序列化为 XML

转载 作者:行者123 更新时间:2023-11-30 21:47:32 26 4
gpt4 key购买 nike

所以我正在使用 MVVM 在 WPF 中构建一个应用程序,我想将各种对象模型数据保存为 XML。使用Serialize an object to XML我可以正确地将对象序列化为 XML,但我遇到的问题是 MVVM 本身。
我无法在 ViewModel 代码的 ICommand 段内直接访问对象的模型(例如,当我点击保存时,它会转到 ViewModel 内的 ICommand 方法)。
我已将模型设置为可序列化问题,我只是无法将其直接传递给我的序列化方法(包含在它自己的静态帮助程序类中),所以即使我没有收到“意外类型”的回复(因为 VieWModel 不可序列化)我最终会得到很多多余的垃圾,而不仅仅是被序列化的 Model 类。

我不确定我是否只是设计不正确,或者是否有更好的方法或...?

附言所有这些字段都被写入适当绑定(bind)的 TextBox 控件中。现在我只是尝试处理名称字段,以避免其他数据类型无法正常工作时出现任何类型的问题。

编辑:根据评论中的要求,现在的目标只是能够在几个文本框中写入一些文本(名字、中间名、姓氏),然后将其保存到 XML 文件中。

有问题的总结模型:

namespace XMLaw.Model
{
[Serializable]
public class ClientModel
{
private string firstName { get; set; }
private string middleName { get; set; }
private string lastName { get; set; }
private DateTime dateOfBirth { get; set; }
private string ssn { get; set; } //Format: AA ## ## ## A, spaces optional
private string address { get; set; }
private string phone { get; set; }

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

#region Name Properties
public string FirstName
{
get { return firstName; }
set
{
if( firstName != value )
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
}
public string MiddleName
{
get { return middleName; }
set
{
if (middleName != value)
{
middleName = value;
OnPropertyChanged("MiddleName");
}
}
}
public string LastName
{
get { return lastName; }
set
{
if (lastName != value)
{
lastName = value;
OnPropertyChanged("LastName");
}
}
}
#endregion

public DateTime DateOfBirth
{
get { return dateOfBirth; }
set
{
if ( dateOfBirth != value )
{
DateTime dt = Convert.ToDateTime(value); //This will probably need to revisited since DateTime objects are fucking stupid
dateOfBirth = dt.Date;
OnPropertyChanged("DateOfBirth");
}
}
}

public string SSN
{
get { return ssn; }
set
{
if( ssn != value)
{
ssn = value;
OnPropertyChanged("SSN");
}
}
}

public string Address
{
get { return address; }
set
{
if( address != value)
{
address = value;
OnPropertyChanged("Address");
}
}
}

public string Phone
{
get { return phone; }
set
{
if( phone != value )
{
phone = value;
OnPropertyChanged("Phone");
}
}
}

}
}

和有问题的ViewModel(调用序列化的Save命令在底部)

namespace XMLaw.ViewModel
{
public class ClientViewModel : INotifyPropertyChanged
{
private ClientModel client;
private string displayMessage;
private ICommand btnSave;

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public ClientViewModel()
{
client = new ClientModel();
}

public ClientModel ClientModel
{
get { return client; }
}

public string DisplayMessage
{
get { return displayMessage; }
set
{
if( displayMessage != value)
{
displayMessage = value;
OnPropertyChanged("DisplayMessage");
}
}
}

public ICommand SaveCommand
{
get
{
if (btnSave == null)
btnSave = new Save();
return btnSave;
}
set { btnSave = value; }
}

protected class Save : ICommand
{

public bool CanExecute(object param) { return true; }
public event EventHandler CanExecuteChanged; //Compiler yells at you if you don't implement this from inhereted ICommand
public void Execute(object param)
{
ClientViewModel viewModel = (ClientViewModel)param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);


//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
}


}
}

还有我厚着脸皮从上面链接拿来的Serailization方法

public static class Helper
{
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
}

最佳答案

将您的客户端模型更改为此:

[Serializable]
public class ClientModel
{
private string firstName;
private string middleName;
private string lastName;
private DateTime dateOfBirth;
private string ssn;
private string address;
private string phone;


public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

#region Name Properties
public string FirstName {
get { return firstName; }
set {
if (firstName != value)
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
}
public string MiddleName {
get { return middleName; }
set {
if (middleName != value)
{
middleName = value;
OnPropertyChanged("MiddleName");
}
}
}
public string LastName {
get { return lastName; }
set {
if (lastName != value)
{
lastName = value;
OnPropertyChanged("LastName");
}
}
}
#endregion

public DateTime DateOfBirth {
get { return dateOfBirth; }
set {
if (dateOfBirth != value)
{
DateTime dt = Convert.ToDateTime(value); //This will probably need to revisited since DateTime objects are fucking stupid
dateOfBirth = dt.Date;
OnPropertyChanged("DateOfBirth");
}
}
}

public string SSN {
get { return ssn; }
set {
if (ssn != value)
{
ssn = value;
OnPropertyChanged("SSN");
}
}
}

public string Address {
get { return address; }
set {
if (address != value)
{
address = value;
OnPropertyChanged("Address");
}
}
}

public string Phone {
get { return phone; }
set {
if (phone != value)
{
phone = value;
OnPropertyChanged("Phone");
}
}
}

}

用法:

 var xx = new ClientModel();
xx.FirstName = "John";
xx.LastName = "Smith";
xx.DateOfBirth = DateTime.Now;

var result = xx.Serialize();

结果:

http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> John Smith 2016-07-11T00:00:00+02:00

编辑:

这段代码:

public void Execute(object param)
{
ClientViewModel viewModel = (ClientViewModel)param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);


//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}

应替换为:

public void Execute(object param)
{
ClientModel model= (ClientModel )param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);


//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}

确保您的 Param 是 ClientModel 类型。

我也强烈建议您了解 how DataBinding works 的基础知识

编辑 2(命令之类的东西):

class Save : ICommand
{
public ClientModel Model { get; set; }
public bool CanExecute(object param) { return true; }
public event EventHandler CanExecuteChanged; //Compiler yells at you if you don't implement this from inhereted ICommand
public void Execute(object param)
{
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(this.Model);


//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
}

用法:

public ICommand SaveCommand
{
get
{
if (btnSave == null)
btnSave = new Save();
btnSave.Model = this.ClientModel;

return btnSave;
}
set { btnSave = value; }
}

关于c# - 将 WPF 中的对象序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com