共用方式為


HOW TO:繪製文字至控制項的背景

更新:2007 年 11 月

將文字字串轉換為 FormattedText 物件,然後將物件繪製至控制項的 DrawingContext,就可以直接將文字繪製至控制項的背景。您也可以使用這個技術來繪製至衍生自 Panel 之物件 (如 CanvasStackPanel) 的背景。

具有自訂文字背景的控制項範例

將文字當做背景顯示的控制項

範例

若要繪製至控制項的背景,請建立新的 DrawingBrush 物件,並將轉換後的文字繪製至物件的 DrawingContext。然後,將新的 DrawingBrush 指派給控制項的背景屬性。

下列程式碼範例顯示如何建立 FormattedText 物件,以及繪製至 LabelButton 物件的背景。

// 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;
    }
}
注意事項:

以下程式碼範例摘錄自完整範例,如需完整程式碼範例,請參閱繪製文字至控制項背景範例

請參閱

概念

繪製格式化的文字

參考

FormattedText