首页 > 解决方案 > 将自定义控件序列化为 JSON 文件

问题描述

在我的 WPF 应用程序中,我正在使用如下所示的自定义控件:

public class FancyLabel : Label
{
    public string FancyProperty  { get; set; }

    public FancyLabel()
    {
        Height = 26;
        BorderBrush = Brushes.Gray;
        Background = Brushes.LightGray;

    }
}

控件具有可自定义的属性,例如“FancyAttr”,可以在运行时更改。在应用程序退出时,我试图将控件/更改保存在 JSON 文件中,如下所示:

string output = JsonConvert.SerializeObject(new FancyLabel(), 
                Formatting.Indented,
           new JsonSerializerSettings
           {
               ReferenceLoopHandling = ReferenceLoopHandling.Ignore
           });
File.WriteAllText("C:/test/savefile.txt", output);

问题是,继承的 Label 类中的所有属性总是被序列化并保存,这导致保存过程非常长并且保存文件很大。有没有办法定义只有“FancyLabel”类中的某些属性或属性被序列化和保存?

标签: c#.netserializationjson.net

解决方案


推荐阅读