C# 如何将文本块动态添加到RelativePanel?
我试图动态地将文本块添加到RelativePanel中,但我想不出一种方法将它们添加到彼此下面。我的目标是在每个文本块下动态添加六个文本块,并交替添加 它应该是这样的:C# 如何将文本块动态添加到RelativePanel?,c#,xaml,uwp,uwp-xaml,C#,Xaml,Uwp,Uwp Xaml,我试图动态地将文本块添加到RelativePanel中,但我想不出一种方法将它们添加到彼此下面。我的目标是在每个文本块下动态添加六个文本块,并交替添加 它应该是这样的: +---------+ | left | | right | | left | | right | | left | | right | +---------+ 我尝试了一个for循环,但这不起作用,因为它一直在同一个位置添加它们,而不是在前一个位置下添加。 .cs代码: protected ov
+---------+
| 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);
}
}
受保护的覆盖无效OnNavigatedTo(NavigationEventArgs e)
{
对于(int i=0;i<3;i++)
{
TextBlock left=新的TextBlock()
{
Name=“left”,
Text=“left”,
前景=新的SolidColorBrush(颜色:白色)
};
TextBlock right=新的TextBlock()
{
Name=“right”,
Text=“右”,
前景=新的SolidColorBrush(颜色为白色),
};
相对性面板下(左、右);
RelativePanel.SetAlignRightWithPanel(左,真);
relativePanel.Children.Add(左);
relativePanel.Children.Add(右);
}
}
.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;
}
}
public void addTextBox(整数计数)
{
布尔左=真;
TextBlock lastAdded=null;
for(int i=0;i
基本上,您可以跟踪最后添加的文本框,以便将下一个文本框放在其下方,并跟踪下一个文本框的位置-左侧或右侧。当您看到答案时,总是如此“简单”。。。谢谢!