Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Actualización: noviembre 2007
Puede dibujar directamente el texto en el fondo de un control; para ello, convierta una cadena de texto en un objeto FormattedText y, a continuación, dibuje el objeto en el objeto DrawingContext del control. También puede utilizar esta técnica para dibujar en el fondo de objetos derivados de Panel, tales como Canvas y StackPanel.
Ejemplo de controles con fondos de texto personalizados
.png)
Ejemplo
Para dibujar en el fondo de un control, cree un nuevo objeto DrawingBrush y dibuje el texto convertido en el DrawingContext del objeto. A continuación, asigne el nuevo DrawingBrush a la propiedad de fondo del control.
En el ejemplo de código siguiente se muestra cómo crear un objeto FormattedText y dibujar en el fondo de un objeto Label y un objeto Button.
// Handle the WindowLoaded event for the window.
private void WindowLoaded(object sender, EventArgs e)
{
// Update the background property of the label and button.
myLabel.Background = new DrawingBrush(DrawMyText("My Custom Label"));
myButton.Background = new DrawingBrush(DrawMyText("Display Text"));
}
// Convert the text string to a geometry and draw it to the control's DrawingContext.
private Drawing DrawMyText(string textString)
{
// Create a new DrawingGroup of the control.
DrawingGroup drawingGroup = new DrawingGroup();
// Open the DrawingGroup in order to access the DrawingContext.
using (DrawingContext drawingContext = drawingGroup.Open())
{
// Create the formatted text based on the properties set.
FormattedText formattedText = new FormattedText(
textString,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Comic Sans MS Bold"),
48,
System.Windows.Media.Brushes.Black // This brush does not matter since we use the geometry of the text.
);
// Build the geometry object that represents the text.
Geometry textGeometry = formattedText.BuildGeometry(new System.Windows.Point(20, 0));
// Draw a rounded rectangle under the text that is slightly larger than the text.
drawingContext.DrawRoundedRectangle(System.Windows.Media.Brushes.PapayaWhip, null, new Rect(new System.Windows.Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0);
// Draw the outline based on the properties that are set.
drawingContext.DrawGeometry(System.Windows.Media.Brushes.Gold, new System.Windows.Media.Pen(System.Windows.Media.Brushes.Maroon, 1.5), textGeometry);
// Return the updated DrawingGroup content to be used by the control.
return drawingGroup;
}
}
Nota
Para obtener el ejemplo de código completo del que se ha extraído el ejemplo de código siguiente, consulte Ejemplo Draw Text to Control Background.