2016-09-14 91 views
2

我想动态地将TextBlocks添加到RelativePanel,但我无法找出一种方法将它们添加到对方下面。我的目标是动态地将六个TextBlocks交替添加到另一个下面。如何将TextBlocks动态添加到RelativePanel?

它应该看起来像这样的事情:

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

我试过一个循环,但是这并不工作,因为这是它保持在同一个地方,而不是按照以前的一个添加。 的.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> 

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

回答

3

你相对接近 - 问题在于你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; 
    } 
} 

基本上你跟踪,最后添加文本框的,所以你可以把它下面的下一个,你跟踪你需要定位下一个 - 左还是右。

+1

当你看到答案时总是这么'简单'...非常感谢! – Denny