c# - 使用 TreeNode 作为用户设置

标签 c# .net winforms treeview settings

我正在尝试使用 TreeNode (System.Windows.Forms.TreeNode) 作为我的应用程序之一的用户设置。

if(treeView.SelectedNode != null)
{
    Properties.Settings.Default.SelectedTreeNode = treeView.SelectedNode;
    Properties.Settings.Default.Save();
}

然后在应用程序加载时我尝试使用该设置

if (Properties.Settings.Default.SelectedTreeNode != null)
    treeView.SelectedNode= Properties.Settings.Default.SelectedTreeNode;

但无论我做什么,当我重新加载应用程序时,Properties.Settings.Default.SelectedTreeNode 始终为 null。

我也尝试过仅使用对象并转换为 TreeNode,但这也不起作用。

我真的不想为此使用字符串设置,并且希望尽可能坚持使用 TreeNode,但是如果无法使用 TreeNode,则序列化的 TreeNode 也可以工作。我只是不太熟悉序列化。

最佳答案

即使您可以在设置中存储 TreeNode,您也无法将反序列化节点分配给 TreeViewSelectedNode 属性。 TreeNode 是引用类型,由于您从设置加载的实例与树中存在的实例不同,因此分配没有意义并且不起作用。 comment中的b点已经提到过作者:陶。

要在设置中保留选定的节点,最好依赖字符串属性。您至少有两个选择:

  1. 在设置中存储节点的Name属性
  2. 在设置中存储节点的 FullPath 属性

选项 1 - 名称属性

每个TreeNode都有一个Name属性,可用于查找节点。

  • 创建节点时为节点分配唯一的键:

    treeView1.Nodes.Add("key", "text");
    
  • 保存数据时,将treeView1.SelectedNode.Name存储在设置中。

  • 根据设置选择节点:

    treeView1.SelectedNode = treeView1.Nodes.Find("some key", true).FirstOrDefault();
    

选项 2 - FullPath 属性

每个TreeNode都有一个FullPath,它获取从根树节点到当前树节点的路径。

The path consists of the labels of all the tree nodes that must be navigated to reach this tree node, starting at the root tree node. The node labels are separated by the delimiter character specified in the PathSeparator property of the TreeView control that contains this node.

  • 创建节点时,不需要进行特殊设置。每个节点都有FullPath

  • 保存数据时,将treeView1.SelectedNode.FullPath存储在设置中。

  • 根据设置选择节点:

    treeView1.SelectedNode = treeView1.Nodes.FindByPath(@"path\to\the\node");
    

在上面的代码中,FindByPath 是一个扩展方法,您可以创建它来按路径查找 ndoe:

using System.Windows.Forms;
public static class TreeViewExtensiona
{
    public static TreeNode FindByPath(this TreeNodeCollection nodes, string path)
    {
        TreeNode found = null;
        foreach (TreeNode n in nodes)
        {
            if (n.FullPath == path)
                found = n;
            else
                found = FindByPath(n.Nodes, path);
            if (found != null)
                return found;
        }
        return null;
    }
}

关于c# - 使用 TreeNode 作为用户设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53308604/

相关文章:

c# - 使用C#进行颜色检测

c# - 如何在 asp :GridView 中使标题标题居中

c# - C# 中的 myCustomer.GetType() 和 typeof(Customer) 有什么区别?

c# - 是否可以在 C# 中创建扩展字段?

.net - 使 Enter 键的行为类似于表单上的 Tab 键

c# - Task.WaitAll() 没有按预期工作

c# - SQLite 引用警告处理器不匹配

c# - Xamarin.forms 上的后台获取

c# - 如何处理一次性对象抛出的异常?

c# - 在我的编译器(生成 IL)中编写单元测试