首页 > 解决方案 > 为什么我不能将自定义文本框放在面板或 groupBox 中?

问题描述

我有一个自定义的 TextBox 控件,定义如下:

class PHTextBox : System.Windows.Forms.TextBox
{
    System.Drawing.Color DefaultColor;
    public string PlaceHolderText { get; set; }

    public PHTextBox(string placeholdertext)
    {
        // get default color of text
        DefaultColor = this.ForeColor;
        // Add event handler for when the control gets focus
        this.GotFocus += (object sender, EventArgs e) =>
        {
            this.Text = String.Empty;
            this.ForeColor = DefaultColor;
        };

        // add event handling when focus is lost
        this.LostFocus += (Object sender, EventArgs e) => {
            if (String.IsNullOrEmpty(this.Text) || this.Text == PlaceHolderText)
            {
                this.ForeColor = System.Drawing.Color.Gray;
                this.Text = PlaceHolderText;
            }
            else
            {
                this.ForeColor = DefaultColor;
            }
        };

        if (!string.IsNullOrEmpty(placeholdertext))
        {
            // change style   
            this.ForeColor = System.Drawing.Color.Gray;

            // Add text
            PlaceHolderText = placeholdertext;
            this.Text = placeholdertext;
        }
    }
}

我正在尝试通过以下方式将自定义文本框添加到面板:

this.tbNombresClienteConfirmarPago = new PHTextBox("Your name");
this.tbNombresClienteConfirmarPago.Location = new System.Drawing.Point(0,0);//(644, 485);
this.tbNombresClienteConfirmarPago.Name = "tbNombresClienteConfirmarPago";
this.tbNombresClienteConfirmarPago.Size = new System.Drawing.Size(203, 20);
this.tbNombresClienteConfirmarPago.TabIndex = 7;
this.tbNombresClienteConfirmarPago.MaxLength = 50;
this.panel1.Controls.Add(this.tbNombresClienteConfirmarPago);

但它不起作用。

我添加了一个属于 Windows 窗体的文本框或按钮,它们被正确地添加到面板中而没有问题。

欢迎任何评论。

升级:

当我想说“它不起作用”时,我指的是对象未显示在面板内的事实。

PHTextBox 在表单中正确显示。

标签: c#winformscustom-controlspanelgroupbox

解决方案


推荐阅读