WPF 在绘图控件(Shape)中添加文字 [2018.7.15]

Q:使用Shape的子类Ellipse画一个圆,如何在圆中添加文字?

A:Shape类中不包含Text属性。可使用Shape类和TextBlock类组合,放到Grid中来实现。

     纯xaml的写法:

<Grid Height="50" Width="50">
    <Ellipse Fill="Yellow" Stroke="Blue" Height="50" Width="50" HorizontalAlignment="Left"></Ellipse>
    <TextBlock Text="5" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>
</Grid>

    纯C#的写法:

Grid nodeGrid = new Grid();

Ellipse nodeCircle = new Ellipse();
nodeCircle.Fill = Brushes.Red;
nodeCircle.Stroke = Brushes.Black;
nodeCircle.Width = 50;
nodeCircle.Height = 50;

TextBlock nodeText = new TextBlock();
nodeText.Text = "5";
nodeText.HorizontalAlignment = HorizontalAlignment.Center;
nodeText.VerticalAlignment = VerticalAlignment.Center;
nodeText.TextAlignment = TextAlignment.Center;

nodeGrid.Children.Add(nodeCircle);
nodeGrid.Children.Add(nodeText);

效果图:


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页