Draw text to the background of a control by accessing the control's DrawingContext.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Draw Text to a Control's Background"
Background="FloralWhite"
Width="800"
Loaded="WindowLoaded">
<StackPanel>
<Label Name="myLabel" Width="200" Height="36" />
<TextBox Name="myTextBox" MaxLength="25" >Sample Text</TextBox>
<Button Name="myButton" Click="OnButtonClick" Width="160" Height="40" />
<Canvas Name="myCanvas" Width ="760" Height="300"/>
</StackPanel>
</Window>
//File:Window.xaml.vb
Imports System
Imports System.Globalization
Imports System.Windows
Imports System.Windows.Media
Namespace WpfApplication1
Public Partial Class Window1
Inherits Window
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Private Sub WindowLoaded(sender As Object, e As EventArgs)
myLabel.Background = New DrawingBrush(DrawMyText("My Custom Label"))
myButton.Background = New DrawingBrush(DrawMyText("Display Text"))
End Sub
Private Function DrawMyText(textString As String) As Drawing
Dim drawingGroup As New DrawingGroup()
Using drawingContext As DrawingContext = drawingGroup.Open()
Dim formattedText As New FormattedText(textString, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, New Typeface("Comic Sans MS Bold"), 48, Brushes.Black)
Dim textGeometry As Geometry = formattedText.BuildGeometry(New Point(20, 0))
drawingContext.DrawRoundedRectangle(Brushes.PapayaWhip, Nothing, New Rect(New Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0)
drawingContext.DrawGeometry(Brushes.Gold, New Pen(Brushes.Maroon, 1.5), textGeometry)
Return drawingGroup
End Using
End Function
Public Sub OnButtonClick(sender As Object, e As EventArgs)
myCanvas.Background = New DrawingBrush(DrawMyText(myTextBox.Text))
End Sub
End Class
End Namespace
Related examples in the same category