Mega Code Archive

 
Categories / C# / WPF
 

Draw text to the background of a control by accessing the controls 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.cs using System; using System.Globalization; using System.Windows; using System.Windows.Media; namespace WpfApplication1 {     public partial class Window1 : Window     {         public Window1() : base()         {             InitializeComponent();         }         private void WindowLoaded(object sender, EventArgs e)          {             myLabel.Background = new DrawingBrush(DrawMyText("My Custom Label"));             myButton.Background = new DrawingBrush(DrawMyText("Display Text"));         }         private Drawing DrawMyText(string textString)         {             DrawingGroup drawingGroup = new DrawingGroup();             using (DrawingContext drawingContext = drawingGroup.Open())             {                 FormattedText formattedText = new FormattedText(                     textString,                     CultureInfo.GetCultureInfo("en-us"),                     FlowDirection.LeftToRight,                     new Typeface("Comic Sans MS Bold"),                     48,                     Brushes.Black                      );                 Geometry textGeometry = formattedText.BuildGeometry(new Point(20, 0));                 drawingContext.DrawRoundedRectangle(Brushes.PapayaWhip, null, 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;             }         }         public void OnButtonClick(object sender, EventArgs e)         {             myCanvas.Background = new DrawingBrush(DrawMyText(myTextBox.Text));         }     } }