如何在WPF中向形状添加文本

12

我正在一个WPF窗口上画圆。问题在于我无法向Circle添加Text。以下是代码:

public Graphics()
{
    InitializeComponent();

    StackPanel myStackPanel = new StackPanel();
    Ellipse myel = new Ellipse();
    SolidColorBrush mscb = new SolidColorBrush();
    mscb.Color = Color.FromArgb(255, 255, 0, 0);
    myel.Fill = mscb;
    myel.StrokeThickness = 2;
    myel.Stroke = Brushes.Black;
    myel.Width = 100;
    myel.Height = 100;
    //string str = "hello";
    myStackPanel.Children.Add(myel);
    this.Content = myStackPanel;
}

请在这方面帮助我。


4
首先,我建议将所有内容转移到XAML中... - H.B.
@H.B. 你知道在圆形上添加文本的方法吗?顺便说一下,我必须通过C#代码来控制它,因为这是必要的。附言:当涉及到XML时,我不太熟悉! :-) - Muhammad Umer
这怎么可能是必要的呢?(同时不要在评论中询问人们是否回答问题...) - H.B.
实际上,我正在使用WPF开发一个AVL树的桌面应用程序。问题在于,我必须提供树的图形布局,即边缘、节点、数据等。这就是为什么我必须向树的节点添加文本,而在我的情况下,这些节点是圆形的! - Muhammad Umer
1
仍然没有任何理由回避XAML。 - H.B.
2个回答

24

形状只是形状,如果您想添加文本,则请将形状和一个带有文本的 TextBlock 添加到公共容器中,使它们彼此叠放,例如没有行或列的 Grid

XAML中:

<Grid>
    <Ellipse Width="100" .../>
    <TextBlock Text="Lorem Ipsum"/>
</Grid>

C#

var grid = new Grid();
grid.Children.Add(new Ellipse { Width = 100, ... });
grid.Children.Add(new TextBlock { Text = "Lorem Ipsum" });

1
先生,您能否给我提供一个例子呢?或者您可以简单地给我提供代码吗?我以前从未处理过图形。 - Muhammad Umer

4

如果您更喜欢直接控制绘制位置,可以在Canvas中使用直接定位:

我的示例定义了一个UI控件,它绘制带有文本的矩形:

XAML

<UserControl x:Class="DrawOnCanvas"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MySample"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <Canvas x:Name="DrawCanvas" Height="30"/>
</Grid>

代码后台:

    // You might e.g. call this in the constructor of DrawOnCanvas
    internal void DrawRectWithText()
    {
        var rect = new System.Windows.Shapes.Rectangle();
        rect.Stroke = new SolidColorBrush(Colors.Black);
        rect.Fill = new SolidColorBrush(Colors.Beige);

        rect.Width = 100;
        rect.Height = 100;

        // Use Canvas's static methods to position the rectangle
        Canvas.SetLeft(rect, 100);
        Canvas.SetTop(rect, 100);

        var text = new TextBlock()
        {
            Text = task.Title,
        };

        // Use Canvas's static methods to position the text
        Canvas.SetLeft(text, 90);
        Canvas.SetTop(text, 90);

        // Draw the rectange and the text to my Canvas control.
        // DrawCanvas is the name of my Canvas control in the XAML code
        DrawCanvas.Children.Add(rect);
        DrawCanvas.Children.Add(text);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接