如何坚持认为是编程做设计时属性的变化? [英] How to persist design time property changes that were made programmatically?

查看:133
本文介绍了如何坚持认为是编程做设计时属性的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我添加了一个编号字符串属性为自定义控制。

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

当控件放置在窗体上,我想构造函数设置为 Guid.NewGuid()的ToString(),但只有当它没有被设置了。

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.

当我手动编辑从设计师这个属性,它增加了一行code到 Designer.cs 文件。我怎样才能做到这一点编程?
具体来说,如何从自定义的控制范围内做到这一点?

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?

推荐答案

我已经创建了一个适合你的requrements样本用户控件。在这种情况下是MyLabel继承自Label。

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

首先,创建保存MyLabel类,并在这里是code该类独立的库:

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;
    }
}

正如你看到我的控制都有一个填充,如果控制在设计模式,并没有值已设置但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.

占优OnPaint事件是那里只是为了看到它不要求实时的实际ID值。

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

这篇关于如何坚持认为是编程做设计时属性的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆