2016-09-14 61 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