Search code examples
c#wpftextblock

How do I use C# to prevent textblocks from overlapping?


I'm trying to use C# to add a TextBlock to my MainWindow at the end of every iteration of a loop.

However, each iteration they're added one on top of the previous one(s). What property of TextBlocks, if any, allows me to keep them from overlapping?

The following is inside a for-loop:

TextBlock result = new TextBlock();

result.Text = [string];

result.Width = 200;
result.Height = 100;
result.Margin = new Thickness(20, 20, 20, 20);

result.Name = "email" + [string];

Analysis_Space.Children.Add(result);

Analysis_Space refers to the main grid of my MainWindow.


Solution

  • Correct use of panel control will help you resolve this. Which panel to use is up to you depending on your GUI needs. Refer this link.

    For example, put new StackPanel on Analysis_Space. Then, add your text area to StackPanel.

    Your new code will look something like below:

    TextBlock result = new TextBlock();
    result.Text = [string];
    result.Width = 200;
    result.Height = 100;
    result.Margin = new Thickness(20, 20, 20, 20);
    result.Name = "email" + [string];
    stackPanel.Children.Add(result);
    

    In above code, stackPanel represents instance of StackPanel which is placed on main grid panel.