How to add text to shapes in WPF

I draw Circle in a WPF window. The problem is that I cannot add Text to the Circle . The code is below:

 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; } 

Please help me in this regard.

+7
source share
2 answers

Shapes are just shapes, if you want to add text, then add a form and a TextBlock with text to a common container that puts them on top of each other, for example. a Grid without rows or columns.

In XAML:

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

WITH#

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

Or you can use direct positioning on the canvas if you prefer direct control over the position of the drawing:

My example defines a user interface control that draws rectangles with text in it:

XAML:

 <UserControl x:Class="DrawOnCanvase" 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> 

Code behind:

  // You might eg call this in the constructor of DrawOnCanves 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 static methods to position the rectangle Canvas.SetLeft(rect, 100); Canvas.SetTop(rect, 100); var text = new TextBlock() { Text = task.Title, }; // Use Canvas 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); } 
0
source

Source: https://habr.com/ru/post/944319/


All Articles