在我的WPF应用程序中,ViewModel具有少量属性,observableCollections等。
当应用关闭或保存点击时,如何将其当前状态保存为文件
我应该使用[Serializable]实现吗?

最好的方法是什么?

public class CustomerViewModel
{
    private Customer obj = new Customer();

    public string TxtCustomerName
    {
        get { return obj.CustomerName; }
        set { obj.CustomerName = value; }
    }

    public string TxtAmount
    {
        get { return Convert.ToString(obj.Amount) ; }
        set { obj.Amount = Convert.ToDouble(value); }
    }
}

最佳答案

最佳方法取决于您的要求。例如,您可以使用内置的DataContractJsonSerializer类序列化您的类,而无需完全修改该类:

CustomerViewModel vm = new CustomerViewModel();
//...

using (MemoryStream ms = new MemoryStream())
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CustomerViewModel));
    ser.WriteObject(ms, vm);
    File.WriteAllText("save.txt", Encoding.UTF8.GetString(ms.ToArray()));
}

您将需要添加对System.Runtime.Serialization.dll的引用。请参阅以下博客文章以获取更多信息:https://www.bytefish.de/blog/enum_datacontractjsonserializer/

另一种流行的高性能第三方JSON序列化器是Json.NET:https://www.newtonsoft.com/json。还有许多其他使用各种格式的解决方案,无论它们是基于文本的还是二进制的。在复杂的情况下,您可能必须编写自己的自定义序列化程序。

关于c# - 保存WPF ViewModel当前状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48403826/

10-11 23:05
查看更多