Denny Denny - 2 months ago 16
C# Question

How to dynamically add TextBlocks to a RelativePanel?

I'm trying to dynamically add TextBlocks to a RelativePanel, but I can't figure out a way to add them below each other. My goal is to dynamically add six TextBlocks under each other and alternating.

It should look like something like this:

+---------+
| left |
| right |
| left |
| right |
| left |
| right |
+---------+


I've tried a for loop, but this doesn't work because it's it keeps adding them at the same place and not under the previous one.
.cs code:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
for (int i = 0; i < 3; i++)
{
TextBlock left = new TextBlock()
{
Name = "left",
Text = "left",
Foreground = new SolidColorBrush(Colors.White)
};
TextBlock right = new TextBlock()
{
Name = "right",
Text = "right",
Foreground = new SolidColorBrush(Colors.White),
};
RelativePanel.SetBelow(left, right);
RelativePanel.SetAlignRightWithPanel(left, true);
relativePanel.Children.Add(left);
relativePanel.Children.Add(right);
}
}


.xaml code:

<ScrollViewer>
<RelativePanel x:Name="relativePanel">

</RelativePanel>
</ScrollViewer>


If this is not possible, is there another way to achieve this? Thanks in advance.

Answer

You were relatively close - the problem is that for the next iteration of your for loop, you loose context of who is "left" and "right" TextBlock and you cannot set the new ones below the old ones. Here's a method to do what you need:

public void AddTextBoxes(int count)
{
    bool left = true;
    TextBlock lastAdded = null;

    for (int i = 0; i < count; i++)
    {
        var currentTextBlock = new TextBlock()
        {
            Name = "textblock" + i.ToString(),
            Text = left ? "left" : "right",
            Foreground = new SolidColorBrush(Colors.White)
        };
        if (lastAdded != null)
        {
            RelativePanel.SetBelow(currentTextBlock, lastAdded);
        }
        if (!left)
        {
            RelativePanel.SetAlignRightWithPanel(currentTextBlock, true);
        }
        relativePanel.Children.Add(currentTextBlock);

        left = !left;
        lastAdded = currentTextBlock;
    }
}

Essentially you keep track of the last added textbox so you can put the next one below it, and you keep track of where you need to position the next one - left or right.