简体   繁体   English

在文本框控件内添加标签

[英]Add label inside textbox control

I want to make a control which inherits from TextBox and which has a label inside which "sticks" to the right side of the text box and which text is not user-editable but rather is set by a property. 我想制作一个控件,该控件继承自TextBox,并且具有一个标签,其中的标签“粘贴”到文本框的右侧,并且该文本不是用户可编辑的,而是由属性设置的。 How can this be done? 如何才能做到这一点? I realize there may be many reasons why this UX is a bad idea, but I have to do it this way. 我意识到,这种UX不好的想法可能有很多原因,但是我必须这样做。

Adapting from Hans Passant's Button inside a winforms textbox answer: 根据winforms文本框内的Hans Passant的Button改编:

public class TextBoxWithLabel : TextBox {

  [DllImport("user32.dll")]
  private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

  Label label = new Label();

  public TextBoxWithLabel() {
    label.BackColor = Color.LightGray;
    label.Cursor = Cursors.Default;
    label.TextAlign = ContentAlignment.MiddleRight;
    this.Controls.Add(label);
  }

  private int LabelWidth() {
    return TextRenderer.MeasureText(label.Text, label.Font).Width;
  }

  public string LabelText {
    get { return label.Text; }
    set {
      label.Text = value;
      SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(LabelWidth() << 16));
      OnResize(EventArgs.Empty);
    }
  }

  protected override void OnResize(EventArgs e) {
    base.OnResize(e);
    int labelWidth = LabelWidth();
    label.Left = this.ClientSize.Width - labelWidth;
    label.Top = (this.ClientSize.Height / 2) - (label.Height / 2);
    label.Width = labelWidth;
    label.Height = this.ClientSize.Height;
  }
}

Result: 结果:

在此处输入图片说明

I will suggest you to create a UserControl with TextBox and a Label docked right. 我建议您创建一个TextBox和一个正确停靠的LabelUserControl That should be pain less and bug free. 那应该更省力,并且没有错误。

As you said you already use TextBox to avoid much refactoring you can add all the properties you used in TextBox as "Proxy properties". 正如您所说的,您已经在使用TextBox来避免大量重构,您可以将在TextBox中使用的所有属性添加为“代理属性”。 Something like this: 像这样:

class MyTextBox : UserControl
{
    public int TextLength { get { return textbox.TextLength; } }
    ...
}

This can help you to avoid much refactoring. 这可以帮助您避免过多的重构。

I would actually create a composit control, or simply a UserControl, and put a label and textbox next to each other. 我实际上会创建一个复合控件,或者只是一个UserControl,然后将标签和文本框彼此相邻放置。 Then you can remove the borders around the textbox and surround them with a borderbox to mimic the normal textbox design. 然后,您可以删除文本框周围的边框,并用边框包围它们,以模仿普通的文本框设计。

Finally I would make sure that the user controls properties, like Text is mapped to the Textbox, so it is easy to use the control as a drop-replacement. 最后,我将确保用户控件的属性(如“ Text已映射到“文本框”,因此可以轻松地将控件用作放置替换。

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

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