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

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

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

     纯xaml的写法:


    
    

    纯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);

效果图:

WPF 在绘图控件(Shape)中添加文字 [2018.7.15]_第1张图片

你可能感兴趣的:(WPF从入门到...)