Search code examples
c#wpfrectangles

How can i add text to a rectangle in c#


Hi I need to be able to generate dynamic rectangles with text. I now have the problem, that im not able to add text over the rectangle

I generate the rectangles here:

public  void ShowAppointements()
    {
        foreach (Termin termin in MainWindow.termine)
        {
            if (termin.week == Int32.Parse(txtWeek.Content.ToString()))
            {
                Rectangle rectangle = new Rectangle();
                Kalender.Children.Add(rectangle);
                Grid.SetRow(rectangle, termin.start + 2);
                Grid.SetColumn(rectangle, termin.day * 2 - 1);
                Grid.SetColumnSpan(rectangle, 2);
                Grid.SetRowSpan(rectangle, termin.end - termin.start);
                rectangle.Fill = termin.color;
            }
        }
    }

Looking into other similar questions the answer was always to just avoid using rectangles but idealy i would like to keep using them.


Solution

  • You could add a TextBlock child to the Grid, in the same place as the Rectangle.

    You could also create a sub-grid with two children, the Rectangle and the TextBlock, as follows:

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

    Or add the TextBlock as child of a Border, instead of having a Rectangle:

    var border = new Border
    {
        Background = termin.color,
        Child = new TextBlock { Text = "Some Text" }
    };
    
    Grid.SetRow(border, termin.start + 2);
    Grid.SetColumn(border, termin.day * 2 - 1);
    Grid.SetColumnSpan(border, 2);
    Grid.SetRowSpan(border, termin.end - termin.start);
    Kalender.Children.Add(border);
    

    Or use an appropriately aligned Label:

    var label = new Label
    {
        Content = "Some Text",
        HorizontalContentAlignment = HorizontalAlignment.Center,
        VerticalContentAlignment = VerticalAlignment.Center,
        Background = termin.color
    };
    
    Grid.SetRow(label, termin.start + 2);
    Grid.SetColumn(label, termin.day * 2 - 1);
    Grid.SetColumnSpan(label, 2);
    Grid.SetRowSpan(label, termin.end - termin.start);
    Kalender.Children.Add(label);