【问题标题】:Unique persistent control identifier唯一持久控制标识符
【发布时间】:2011-11-19 03:03:46
【问题描述】:

我们拥有什么
我们有一些复杂的 winforms 控件。为了存储它的状态,我们使用了一些自定义的序列化类。假设我们已将其序列化为 xml。现在我们可以将此 xml 保存为用户目录中的文件或将其包含在另一个文件中....
但是……

问题是
如果用户在他的 winform 应用程序中创建了几个这样的控件(在设计时),为了知道哪些保存的配置属于这些控件中的哪一个,使用哪个唯一标识符更好?

所以这个标识符应该:

  • 在应用程序启动时保持不变
  • 自动给定(或已经给定,就像我们可以假设 Control.Name 始终存在)
  • 跨应用程序唯一

我认为人们可以想象几种方法来做到这一点,并且我相信可能会有一些默认的方法来做到这一点。

什么更好用?为什么?

【问题讨论】:

    标签: c# winforms configuration uid


    【解决方案1】:

    我一直在使用由完整的控制层次结构树组成的复合标识符。假设您的表单名称是 Form1,那么您有一个分组框 Groupbox1 和一个文本框 TextBox1,复合标识符将是 Form1/Groupbox1/TextBox1。

    如果你想关注这个,这里是详细信息:

    http://netpl.blogspot.com/2007/07/context-help-made-easy-revisited.html

    【讨论】:

      【解决方案2】:

      这个小扩展方法可以完成工作:

      public static class FormGetUniqueNameExtention
      {
          public static string GetFullName(this Control control)
          {
              if(control.Parent == null) return control.Name;
              return control.Parent.GetFullName() + "." + control.Name;
          }
      }
      

      它返回类似'Form1._flowLayoutPanel.label1'的东西

      用法:

      Control aaa;
      Dictionary<string, ControlConfigs> configs;
      ...
      configs[aaa.GetFullName()] = uniqueAaaConfig;
      

      【讨论】:

        【解决方案3】:

        这是我最终创建的用于定义唯一名称的方法,该名称包括表单的全名(及其命名空间),然后是相关控件上方的每个父控件。所以它最终可能是这样的:

        MyCompany.Inventory.SomeForm1.SomeUserControl1.SomeGroupBox1.someTextBox1

            static string GetUniqueName(Control c)
            {
                StringBuilder UniqueName = new StringBuilder();
                UniqueName.Append(c.Name);
                Form OwnerForm = c.FindForm();
        
                //Start with the controls immediate parent;
                Control Parent = c.Parent;
                while (Parent != null)
                {
                    if (Parent != OwnerForm)
                    {
                        //Insert the parent control name to the beginning of the unique name
                        UniqueName.Insert(0, Parent.Name + "."); 
                    }
                    else
                    {
                        //Insert the form name along with it's namespace to the beginning of the unique name
                        UniqueName.Insert(0, OwnerForm.GetType() + "."); 
                    }
        
                    //Advance to the next parent level.
                    Parent = Parent.Parent;
                }
        
                return UniqueName.ToString();
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-06-30
          • 1970-01-01
          • 2012-06-01
          • 1970-01-01
          • 2014-03-05
          • 2012-06-02
          • 2012-11-21
          相关资源
          最近更新 更多