如何动态地将TextBlocks添加到RelativePanel?

Den*_*nny 3 c# xaml uwp uwp-xaml

我正在尝试动态地将TextBlocks添加到RelativePanel,但我无法找到将它们添加到彼此之下的方法.我的目标是在彼此之下动态添加六个TextBlock并交替.

它应该看起来像这样:

+---------+
| left    |
|   right |
| left    |
|   right |
| left    |
|   right |
+---------+
Run Code Online (Sandbox Code Playgroud)

我已经尝试了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);
    }
}
Run Code Online (Sandbox Code Playgroud)

.xaml代码:

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

    </RelativePanel>
</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

如果这是不可能的,还有另一种方法来实现这一目标吗?提前致谢.

Ale*_*nea 5

你是相对接近的 - 问题是,对于你的for循环的下一次迭代,你松开了谁是"左"和"右"的上下文,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,您可以跟踪最后添加的文本框,这样您就可以将下一个文本框放在它下面,并跟踪下一个位置所需的位置 - 左侧或右侧.