VB.NET多色标签

时间:2011-11-11 11:51:31

标签: vb.net

我想在单标签控制器中为文本设置多种颜色

e.g。

label1.Text = " $ 480.00 "

我想要的是红色的字符$和蓝色的$后的其他数字或字符。

我没有单独的数字标签和$

1 个答案:

答案 0 :(得分:3)

标签本身不能这样做,因此您可以使用只读的RichTextBox控件,也可以自己制作标签控件。

以最简单的形式:

Public Class ColorLabel
  Inherits Control

  Private _Money As Decimal = 0

  Property Money() As Decimal
    Get
      Return _Money
    End Get
    Set(ByVal value As Decimal)
      _Money = value
      Me.Invalidate()
    End Set
  End Property

  Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
    MyBase.OnPaint(e)

    Dim moneyText As String = String.Format("{0:N2}", _Money)
    Dim dollarWidth As Integer = TextRenderer.MeasureText(e.Graphics, "$", Me.Font).Width
    Dim moneyWidth As Integer = TextRenderer.MeasureText(e.Graphics, moneyText, Me.Font).Width

    TextRenderer.DrawText(e.Graphics, "$", Me.Font, New Point(Me.ClientSize.Width - (dollarWidth + moneyWidth + 2), 2), Color.Red)
    TextRenderer.DrawText(e.Graphics, moneyText, Me.Font, New Point(Me.ClientSize.Width - (moneyWidth + 2), 2), Color.Blue)
  End Sub

End Class

结果:

enter image description here