在文本框控件内添加标签

Add label inside textbox control(在文本框控件内添加标签)
本文介绍了在文本框控件内添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个从 TextBox 继承的控件,它有一个标签,其中粘贴"到文本框的右侧,并且该文本不是用户可编辑的,而是由属性设置的.如何才能做到这一点?我意识到这个 UX 是一个坏主意的原因可能有很多,但我必须这样做.

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. 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.

推荐答案

改编自 Hans Passant 的 Winforms 文本框内的按钮答案:

Adapting from Hans Passant's Button inside a winforms textbox answer:

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

结果:

这篇关于在文本框控件内添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)