TreeNodeSelectionGroupInfo.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Newtonsoft.Json;
  6. namespace MECF.Framework.UI.Client.ClientBase.Tree
  7. {
  8. public class TreeNodeSelectionGroupInfo
  9. {
  10. #region Constructors
  11. public TreeNodeSelectionGroupInfo()
  12. {
  13. SelectedTerminalNodes = new List<string>();
  14. }
  15. public TreeNodeSelectionGroupInfo(IEnumerable<string> collection)
  16. {
  17. SelectedTerminalNodes = new List<string>(collection);
  18. }
  19. #endregion
  20. #region Properties
  21. public List<string> SelectedTerminalNodes
  22. {
  23. get;
  24. }
  25. #endregion
  26. #region Methods
  27. /// <summary>
  28. /// 从指定的文件恢复节点选择
  29. /// </summary>
  30. /// <param name="fileName"></param>
  31. internal static void RecoveryFromJsonFile(string fileName, TreeNode treeRoot)
  32. {
  33. if (treeRoot == null)
  34. throw new ArgumentNullException(nameof(treeRoot));
  35. if (string.IsNullOrEmpty(fileName))
  36. throw new ArgumentException("the file name is not specified.", nameof(fileName));
  37. var json = File.ReadAllText(fileName);
  38. var info = JsonConvert.DeserializeObject<TreeNodeSelectionGroupInfo>(json);
  39. // 如果没有正确恢复Preset Group文件,则提示错误
  40. if (info.SelectedTerminalNodes == null)
  41. throw new JsonException($"the file of preset group might be incorrect.");
  42. treeRoot.UnselectAll();
  43. treeRoot.SuspendUpdate();
  44. var flattenTree = treeRoot.Flatten(true);
  45. info.SelectedTerminalNodes.ForEach(x =>
  46. {
  47. var matched = flattenTree.FirstOrDefault(f => f.ToString() == x.ToString());
  48. if (matched != null)
  49. matched.IsSelected = true;
  50. });
  51. treeRoot.ResumeUpdate();
  52. }
  53. internal static void SaveToJsonFile(string fileName, TreeNode treeRoot)
  54. {
  55. if (treeRoot == null)
  56. throw new ArgumentNullException(nameof(treeRoot));
  57. if (string.IsNullOrEmpty(fileName))
  58. throw new ArgumentException("the file name is not specified.", nameof(fileName));
  59. var selectedNodes =
  60. treeRoot.Flatten(true)
  61. .Where(x => x.IsSelected == true)
  62. .Select(x=>x.ToString());
  63. var info = new TreeNodeSelectionGroupInfo(selectedNodes);
  64. var json = JsonConvert.SerializeObject(info, Formatting.Indented);
  65. File.WriteAllText(fileName, json);
  66. }
  67. #endregion
  68. }
  69. }