Unique persistent control identifier
What we have
We have some complex winforms control. To store its state we use some custom serialized class. Lets say we've serialized it to xml. Now we could save this xml as a file in User directory or to include it in some another file.... But...The qu开发者_C百科estion is,
if user creates several such controls across his winform application (at design time), what unique identifier is better to use in order to know which of the saved configs belongs to which of these controls?So this identifier should:
- Stay the same across application launches
- Automatic given (or already given, like we can assume that Control.Name is always there)
- Unique across application
I think one could imagine several ways of doing it and I believe there are might be some default ways of doing it.
What is better to use? Why?
This small extension method does the work:
public static class FormGetUniqueNameExtention
{
public static string GetFullName(this Control control)
{
if(control.Parent == null) return control.Name;
return control.Parent.GetFullName() + "." + control.Name;
}
}
It returns something like 'Form1._flowLayoutPanel.label1'
Usage:
Control aaa;
Dictionary<string, ControlConfigs> configs;
...
configs[aaa.GetFullName()] = uniqueAaaConfig;
I've been using a compound indentifier made of a full tree of control hierarchy. Assuming that your form name is Form1, then you have a groupbox Groupbox1 and a textbox TextBox1, the compound identifier would be Form1/Groupbox1/TextBox1.
If you'd like to follow this, here are the details:
http://netpl.blogspot.com/2007/07/context-help-made-easy-revisited.html
This is the method I've ended up creating to define a unique name that includes the full name of the form (with it's namespace) then each parent control above the control in question. So it could end up being something like:
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();
}
精彩评论