2015-12-16 45 views
-1

我有一個覆蓋大部分屏幕的空白網格。我想把任何數量的非重疊矩形放在矩形中居中的文本上。我的矩形似乎只出現在一個地方,而文字只在左上角。不知道如何將矩形中的文本居中,或者在第一個矩形下面放置第二個矩形。我已經試過代碼如下所示:在網格上的矩形和矩形放置中居中文本

private void Terminal(string text) 
{ 
    // Add a Rectangle Element 
    TextBlock mytext = new TextBlock(); 
    mytext.Text = text; 
    mytext.TextAlignment = TextAlignment.Left; 
    mytext.TextWrapping = TextWrapping.Wrap; 
    Rectangle myRect = new System.Windows.Shapes.Rectangle(); 
    myRect.Stroke = System.Windows.Media.Brushes.Black; 
    myRect.Fill = System.Windows.Media.Brushes.Plum; 
    myRect.HorizontalAlignment = HorizontalAlignment.Left; 
    myRect.VerticalAlignment = VerticalAlignment.Top; 
    myRect.Height = 40; 
    myRect.Width = 100; 
    myRect.RadiusX = 20; // round the corners 
    myRect.RadiusY = 20; // round the corners 
    grid.Children.Add(myRect); 
    grid.Children.Add(mytext); 
} 

這需要是動態的所以沒有在文件名爲.xaml是要創造對他們的矩形或文本的工作。

回答

0

我不得不去看看VS是肯定的,但:

mytext.TextAlignment = TextAlignment.Left; 

你試過TextAlignment.Center呢?

0

對於網格,您可能需要計算邊距。 或將網格分成幾個部分。

另一種方法是根據需要使用StackPanel或WrapPanel。

private void Terminal(string text) 
    { 
     Grid aGrid = new Grid() 
     { 
      Height=40, 
      Width=100 
     }; 
     TextBlock myText = new TextBlock() 
     { 
      Text = text, 
      HorizontalAlignment = HorizontalAlignment.Center, 
      VerticalAlignment = VerticalAlignment.Center 
     }; 
     Rectangle myRect = new Rectangle() 
     { 
      Stroke = Brushes.Black, 
      Fill = Brushes.Plum, 
      Height = 40, 
      Width = 100, 
      RadiusX = 20, 
      RadiusY = 20 
     }; 

     aGrid.Children.Add(myRect); 
     aGrid.Children.Add(myText); 
     mainStackPanel.Children.Insert(0, aGrid); 
    }