2016-09-14 12 views
2

私は動的にTextBlocksをRelativePanelに追加しようとしていますが、それらを互いに下に追加する方法を見つけることはできません。私の目標は、6つのTextBlockを動的に追加して交互に追加することです。RelativePanelにTextBlockを動的に追加する方法は?

それは次のようなもののようになります。それは、同じ場所ではなく、以前のいずれかの下にそれらを追加し続けますので、私はループのために試してみたが、これは動作しません

+---------+ 
| 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

関連する問題