Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

how to add text in rectangle with code behind wpf

I want to add textblock or label inside rectangle which is creating with code behind Can anyone help me?

  for (int i = 0; i < _RoomX.Count; i++)
        {
            _RoomX[i] = (Convert.ToDouble(_RoomX[i]) * 20).ToString();
            _RoomY[i] = (Convert.ToDouble(_RoomY[i]) * 20).ToString();

            var rectangle = new Rectangle()
            {

                Stroke = Brushes.Black,
                Fill = brush,
                Width = Convert.ToDouble(_RoomX[i]),
                Height = Convert.ToDouble(_RoomY[i]),
                Margin = new Thickness(
                    left: 15,
                    top: 50,
                    right: 0,
                    bottom: 0),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top

            };
            mainCanvas.Children.Add(rectangle);
        }

Upvotes: 0

Views: 9622

Answers (1)

Bathineni
Bathineni

Reputation: 3496

well rectangle is not a content control it is derived from shape object... we cannot use it as a panel.

instead of rectangle you can use a border..

if your requirement demands a Rectangle then what you can do is... create a Grid> then add rectangle to that Grid> and create a textblock and add it to same grid... since grid is not physically visible it appears like text added to rectangle ..

i will try to post a sample

Edit: following code will help you to understand it better

for (int i = 0; i < _RoomX.Count; i++)
        {
            _RoomX[i] = (Convert.ToDouble(_RoomX[i]) * 20).ToString();
            _RoomY[i] = (Convert.ToDouble(_RoomY[i]) * 20).ToString();

            var rectangle = new Rectangle()
            {

                Stroke = Brushes.Black,
                Fill = brush,
                Width = Convert.ToDouble(_RoomX[i]),
                Height = Convert.ToDouble(_RoomY[i]),
                Margin = new Thickness(
                    left: 15,
                    top: 50,
                    right: 0,
                    bottom: 0),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top

            };

            Grid grid = new Grid();
            grid.Children.Add(rectangle);
            TextBlock textblock = new TextBlock();
            textblock.Text = "Text to add";
            grid.Children.Add(textblock);

            mainCanvas.Children.Add(grid);
        }

Upvotes: 3

Related Questions