Sic03/Sicentury.Core/Tree/TreeNodeSelectionGroupInfo.cs

90 lines
2.6 KiB
C#
Raw Normal View History

2022-08-05 13:22:33 +08:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace Sicentury.Core.Tree
{
2022-08-05 13:48:33 +08:00
public class TreeNodeSelectionGroupInfo
2022-08-05 13:22:33 +08:00
{
#region Constructors
2022-08-05 13:48:33 +08:00
public TreeNodeSelectionGroupInfo()
2022-08-05 13:22:33 +08:00
{
SelectedTerminalNodes = new List<string>();
}
2022-08-05 13:48:33 +08:00
public TreeNodeSelectionGroupInfo(IEnumerable<string> collection)
2022-08-05 13:22:33 +08:00
{
SelectedTerminalNodes = new List<string>(collection);
}
#endregion
#region Properties
public List<string> SelectedTerminalNodes
{
get;
}
#endregion
#region Methods
/// <summary>
/// 从指定的文件恢复节点选择
/// </summary>
/// <param name="fileName"></param>
2022-08-05 13:48:33 +08:00
internal static void RecoveryFromJsonFile(string fileName, TreeNode treeRoot)
2022-08-05 13:22:33 +08:00
{
if (treeRoot == null)
throw new ArgumentNullException(nameof(treeRoot));
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("the file name is not specified.", nameof(fileName));
var json = File.ReadAllText(fileName);
2022-08-05 13:48:33 +08:00
var info = JsonConvert.DeserializeObject<TreeNodeSelectionGroupInfo>(json);
2022-08-05 13:22:33 +08:00
// 如果没有正确恢复Preset Group文件则提示错误
if (info.SelectedTerminalNodes == null)
throw new JsonException($"the file of preset group might be incorrect.");
treeRoot.UnselectAll();
treeRoot.SuspendUpdate();
var flattenTree = treeRoot.Flatten(true);
info.SelectedTerminalNodes.ForEach(x =>
{
var matched = flattenTree.FirstOrDefault(f => f.ToString() == x.ToString());
if (matched != null)
matched.IsSelected = true;
});
treeRoot.ResumeUpdate();
}
2022-08-05 13:48:33 +08:00
internal static void SaveToJsonFile(string fileName, TreeNode treeRoot)
2022-08-05 13:22:33 +08:00
{
if (treeRoot == null)
throw new ArgumentNullException(nameof(treeRoot));
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("the file name is not specified.", nameof(fileName));
var selectedNodes =
treeRoot.Flatten(true)
.Where(x => x.IsSelected == true)
.Select(x=>x.ToString());
2022-08-05 13:48:33 +08:00
var info = new TreeNodeSelectionGroupInfo(selectedNodes);
2022-08-05 13:22:33 +08:00
var json = JsonConvert.SerializeObject(info, Formatting.Indented);
File.WriteAllText(fileName, json);
}
#endregion
}
}