gpt4 book ai didi

c# - 如何将 TextBlocks 动态添加到 RelativePanel?

转载 作者:行者123 更新时间:2023-11-30 14:49:05 24 4
gpt4 key购买 nike

我正在尝试将 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 循环的下一次迭代,你失去了谁是“左”和“右”的上下文 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;
}
}

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

关于c# - 如何将 TextBlocks 动态添加到 RelativePanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com