How to persist design time property changes that were made programmatically?

微笑、不失礼 提交于 2019-12-24 05:43:51

问题


I have a custom control that I added an Id string property to.

When the control is placed on a form, I want the constructor to set this to Guid.NewGuid().ToString(), but only if it hasn't been set before.

When I manually edit this property from the designer, it adds a line of code to the Designer.cs file. How can I do that programmatically?
Specifically, how to do it from within the custom control?


回答1:


I have created sample usercontrol that fits your requrements. In this case is "MyLabel" that inherits from Label.

First create separate library that holds MyLabel class and here is the code for this class:

public class MyLabel: Label
{
    public string ID { get; set; }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();
        if (this.DesignMode && string.IsNullOrEmpty(this.ID))
        {
            this.ID = Guid.NewGuid().ToString();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        this.Text = this.ID;
    }
}

As you see my control has ID property that is populated if control is in design mode and no value has been set yet. Checking design mode is important so value will not change if you reopen the project.

Override for OnPaint event is there just to see actual ID value in real time it's not required.




回答2:


I believe what you need is Properties.Settings. See MSDN page.

You can set these to default values during design, or load and save at runtime.
Example: with the designer, create a new user scoped string[] named IDs. Then in your constructor, something like this

string ID = "";
if (Properties.Settings.Default.IDs!=null && Properties.Settings.Default.IDs.Length>0) {
   ID = Properties.Settings.Default.IDs[0];
}
else {
   ID = "random";
   Properties.Settings.Default.IDs = new string[1];
   Properties.Settings.Default.IDs[0] = ID;
   Properties.Settings.Default.Save();
}

This will use the first element of the stored array if there is one, or it will create a new string if there isn't, and persist it (so it will be read from the settings next time you run the program).



来源:https://stackoverflow.com/questions/13549351/how-to-persist-design-time-property-changes-that-were-made-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!