2017-10-04 60 views
0

嗨我需要能夠生成帶有文本的動態矩形。我現在有這個問題,那我不是能夠在矩形中添加文本我如何添加文本到c中的矩形#

我產生這裏的矩形:

public void ShowAppointements() 
    { 
     foreach (Termin termin in MainWindow.termine) 
     { 
      if (termin.week == Int32.Parse(txtWeek.Content.ToString())) 
      { 
       Rectangle rectangle = new Rectangle(); 
       Kalender.Children.Add(rectangle); 
       Grid.SetRow(rectangle, termin.start + 2); 
       Grid.SetColumn(rectangle, termin.day * 2 - 1); 
       Grid.SetColumnSpan(rectangle, 2); 
       Grid.SetRowSpan(rectangle, termin.end - termin.start); 
       rectangle.Fill = termin.color; 
      } 
     } 
    } 

尋找其他類似的問題的回答總是,只是避免使用矩形但idealy我想繼續使用它們。

+2

把TextBlock放到同一個Grid單元格中。 – Clemens

回答

1

您可以將TextBlock子項添加到網格中與矩形相同的位置。

您還可以創建一個分格,有兩個孩子,矩形與文本塊,如下所示:

Grid subGrid = new Grid(); 
subGrid.Children.Add(rectangle); 
TextBlock textblock = new TextBlock(); 
textblock.Text = "Text to add"; 
subGrid.Children.Add(textblock); 

Kalender.Children.Add(grid); 

或添加的TextBlock作爲邊境的孩子,而不是有一個矩形:

var border = new Border 
{ 
    Background = termin.color, 
    Child = new TextBlock { Text = "Some Text" } 
}; 

Grid.SetRow(border, termin.start + 2); 
Grid.SetColumn(border, termin.day * 2 - 1); 
Grid.SetColumnSpan(border, 2); 
Grid.SetRowSpan(border, termin.end - termin.start); 
Kalender.Children.Add(border); 

或者使用適當對準標籤:

var label = new Label 
{ 
    Content = "Some Text", 
    HorizontalContentAlignment = HorizontalAlignment.Center, 
    VerticalContentAlignment = VerticalAlignment.Center, 
    Background = termin.color 
}; 

Grid.SetRow(label, termin.start + 2); 
Grid.SetColumn(label, termin.day * 2 - 1); 
Grid.SetColumnSpan(label, 2); 
Grid.SetRowSpan(label, termin.end - termin.start); 
Kalender.Children.Add(label); 
-1

沒錯原來答案w ^真的很簡單,我是個白癡。 我是這樣解決的:

public void ShowAppointements() 
    { 
     foreach (Termin termin in MainWindow.termine) 
     { 
      if (termin.week == Int32.Parse(txtWeek.Content.ToString())) 
      { 
       Rectangle rectangle = new Rectangle(); 
       TextBlock textblock = new TextBlock(); 
       Kalender.Children.Add(rectangle); 
       Kalender.Children.Add(textblock); 
       Grid.SetRow(rectangle, termin.start + 2); 
       Grid.SetColumn(rectangle, termin.day * 2 - 1); 
       Grid.SetColumnSpan(rectangle, 2); 
       Grid.SetRowSpan(rectangle, termin.end - termin.start); 
       Grid.SetRow(textblock, termin.start + 2); 
       Grid.SetColumn(textblock, termin.day * 2 - 1); 
       Grid.SetColumnSpan(textblock, 2); 
       Grid.SetRowSpan(textblock, termin.end - termin.start); 
       textblock.Text = termin.project + "\n" + termin.employee; 
       rectangle.Fill = termin.color; 

      } 
     } 
    }