How to: Draw Text to a Control's Background

You can draw text directly to the background of a control by converting a text string to a FormattedText object, and then drawing the object to the control's DrawingContext. You can also use this technique for drawing to the background of objects derived from Panel, such as Canvas and StackPanel.

Example of controls with custom text backgrounds

Controls displaying text as background

To draw to the background of a control, create a new DrawingBrush object and draw the converted text to the object's DrawingContext. Then, assign the new DrawingBrush to the control's background property.

The following code example shows how to create a FormattedText object and draw to the background of a Label and Button object.

		' Handle the WindowLoaded event for the window.
		Private Sub WindowLoaded(ByVal sender As Object, ByVal e As EventArgs)
			' Update the background property of the label and button.
			myLabel.Background = New DrawingBrush(DrawMyText("My Custom Label"))
			myButton.Background = New DrawingBrush(DrawMyText("Display Text"))
		End Sub

		' Convert the text string to a geometry and draw it to the control's DrawingContext.
		Private Function DrawMyText(ByVal textString As String) As Drawing
			' Create a new DrawingGroup of the control.
			Dim drawingGroup As New DrawingGroup()

			' Open the DrawingGroup in order to access the DrawingContext.
			Using drawingContext As DrawingContext = drawingGroup.Open()
				' Create the formatted text based on the properties set.
				Dim formattedText As New FormattedText(textString, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Comic Sans MS Bold"), 48, Brushes.Black) ' This brush does not matter since we use the geometry of the text.

				' Build the geometry object that represents the text.
				Dim textGeometry As Geometry = formattedText.BuildGeometry(New Point(20, 0))

				' Draw a rounded rectangle under the text that is slightly larger than the text.
				drawingContext.DrawRoundedRectangle(Brushes.PapayaWhip, Nothing, New Rect(New Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0)

				' Draw the outline based on the properties that are set.
				drawingContext.DrawGeometry(Brushes.Gold, New Pen(Brushes.Maroon, 1.5), textGeometry)

				' Return the updated DrawingGroup content to be used by the control.
				Return drawingGroup
			End Using
		End Function
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft