如何将 TextBlocks 动态添加到 RelativePanel?

How to dynamically add TextBlocks to a RelativePanel?

我正在尝试将 TextBlock 动态添加到 RelativePanel,但我想不出一种将它们添加到彼此下方的方法。我的目标是在彼此下方动态添加六个 TextBlocks 并交替。

它应该看起来像这样:

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

我试过 for 循环,但这不起作用,因为它一直在同一个地方添加它们,而不是在前一个循环之下。 .cs代码:

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 代码:

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

    </RelativePanel>
</ScrollViewer>

如果这不可能,是否有其他方法可以实现?提前致谢。

你相对接近 - 问题是对于 for 循环的下一次迭代,你失去了谁是 "left" 和 "right" TextBlock 的上下文,你无法设置新的在旧的下面。 这里有一种方法可以满足您的需求:

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

基本上,您会跟踪最后添加的文本框,以便可以将下一个文本框放在它下面,并且您会跟踪需要放置下一个文本框的位置 - 左侧或右侧。