简体   繁体   English

如何在用户控件C#WinForm中设置标签的文本

[英]How to set text of a label inside a usercontrol c# winform


I am going to design a userControl which contains a textbox and a label. 我将设计一个包含文本框和标签的userControl。 How can I set a public property for label text? 如何设置标签文本的公共属性?

this is my code: 这是我的代码:

public partial class CurrencyTextBoxWithLable : UserControl
{
    public CurrencyTextBoxWithLable()
    {
        InitializeComponent();   
    }

    private string _lblText;

    public string LabelText 
    {
        get
        {
            return _lblText;
        }
        set
        {
            _lblText = value;
        }
    }
}

But it doesn't work... Any help will be appreciated. 但这是行不通的。任何帮助将不胜感激。

DesignerCode: 设计器代码:

private void InitializeComponent()
    {
        this.label1 = new System.Windows.Forms.Label();
        this.textBox1 = new System.Windows.Forms.TextBox();
        this.SuspendLayout();
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 6);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(35, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = this.LabelText;//Oooppsss!

} }

在此处输入图片说明

It's not working because you are overwriting your value from properties. 它不起作用,因为您正在覆盖属性的值。 In designer file you are calling this: 在设计器文件中,您将此称为:

this.label1.Text = this.LabelText;

Looking at your getter, it's returning _lblText value: 查看您的吸气剂,它正在返回_lblText值:

get
{
    return _lblText;
}

Since it's not initialized the value of _lblText is empty string (""). 由于尚未初始化,因此_lblText值为空字符串(“”)。 Try setting value of _lblText to some initial value and run your code again. 尝试将_lblText值设置为某个初始值,然后再次运行代码。 For example add this: 例如,添加以下内容:

private string _lblText = "Label1";

EDIT: 编辑:

When you add label to your form it looks like this: 当您将标签添加到表单时,它看起来像这样:

this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(46, 17);
this.label1.TabIndex = 0;
this.label1.Text = "label1";

So, "label1" is the same value as in properties. 因此,“ label1”与属性中的值相同。 When you change it in properties, to lets say Test label string , designer will have value of: 当您更改属性时,可以说Test label string ,设计器将具有以下值:

this.label1.Test = "Test label string";

Try removing and adding your label again if it's not working for you. 如果不适合您,请尝试再次删除并添加标签。 You should be able to change it's value through properties again. 您应该能够再次通过属性更改其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM