我如何添加文本到c中的矩形#

我如何添加文本到c中的矩形#

问题描述:

嗨我需要能够生成带有文本的动态矩形。我现在有这个问题,那我不是能够在矩形中添加文本我如何添加文本到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

您可以将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); 

没错原来答案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; 

      } 
     } 
    }