2017-10-12 80 views
0

我有以下的文本塊,我似乎無法得到文本對齊:文本塊不對齊

TextBlock headerBlock; 
Canvas headerContainer; 

public setLayout() 
{ 
    headerContainer= new Canvas(); 
    headerContainer.Background = new Brushes.Black; 

    headerBlock= new TextBlock(); 
    headerBlock.FontSize = 10; 
    headerBlock.Text = "This must be centered"; 
    headerBlock.TextAlignment = System.Windows.TextAlignment.Center; 
    headerBlock.Foreground = Brushes.White; 
    headerBlock.Padding = new System.Windows.Thickness(20); 


    headerContainer.Children.Add(headerBlock); 

} 

出於某種原因,TextAlignment不對齊文本。有什麼我可以添加到強制headerBlock文本對齊中心?

+0

您可以在''XAML''中使用'VerticalAlignment = Center'。你嘗試過嗎? – Brian

回答

2

此行爲是由於畫布

=>畫布根據像素位置組織元素。 用網格取代你的畫布,它會工作。

你還必須寫什麼zambonee建議:

TextAlignment將調整控制內的文本。 HorizontalAlignmentVerticalAlignment將使控件在其容器內部對齊。

=>與兩個玩,以獲得你所需要的。

+0

將網格更改爲畫布,謝謝! – lost9123193

0

TextBlock未擴展爲填充其父項,並可能卡塞在其父項的左上角。試試這個

headerBlock.HorizontalAlignment = HorizontalAlignment.Center; //or Stretch with TextAlignment = Center 
headerBlock.VerticalAlignment = VerticalAlignment.Center; //or Stretch 
+0

啊我試過這個,它似乎沒有工作。我在代碼中添加了1行代碼,headerContainer廣告代碼塊,認爲我不確定它是否會影響對齊 – lost9123193

+0

Canvas忽略其子元素的對齊屬性。 – Clemens