2010-12-13 79 views
0

我必須創建一個來顯示KEY VALUE類的東西。WPF:Grid中的動態標籤添加

我試過下面的代碼,但與重疊輸出搞砸了。我相信,我需要創建Grid RowDefinitions和ColumnDefinitions,但無法實現它。請幫幫我。

XAML:

<Window x:Class="GrideLabel.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid Name="LabelGrid"></Grid> 
</Window> 

後面的代碼:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      AddLabelDynamically(); 
     } 

     private void AddLabelDynamically() 
     { 
      for (int i = 0; i < 3; i++) 
      { 
       Label nameLabel = new Label(); nameLabel.Content = "KEY :"+i.ToString(); 
       Label dataLabel = new Label(); dataLabel.Content = "VALUE :"+i.ToString(); 
       //I want to creatre the Seperate coloum and row to display KEY 
       // VALUE Pair distinctly 
       this.LabelGrid.Children.Add(nameLabel); 
       this.LabelGrid.Children.Add(dataLabel); 
      } 
     } 
    } 

回答

0

你必須定義行和列的定義,並指定行和列的子控件。代碼如下:

private void AddLabelDynamically() 
    { 
     this.LabelGrid.ColumnDefinitions.Clear(); 
     this.LabelGrid.RowDefinitions.Clear(); 

     this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition()); 
     this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition()); 

     for (int i = 0; i < 3; i++) 
     { 
      this.LabelGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); 

      Label nameLabel = new Label(); nameLabel.Content = "KEY :" + i.ToString(); 
      Label dataLabel = new Label(); dataLabel.Content = "VALUE :" + i.ToString(); 

      Grid.SetRow(nameLabel, i); 
      Grid.SetRow(dataLabel, i); 

      Grid.SetColumn(nameLabel, 0); 
      Grid.SetColumn(dataLabel, 1); 

      //I want to creatre the Seperate coloum and row to display KEY 
      // VALUE Pair distinctly 
      this.LabelGrid.Children.Add(nameLabel); 
      this.LabelGrid.Children.Add(dataLabel); 
     } 
    }