TextBlock應居中位置x(或方向垂直時爲y)。 我實現:如何將TextBlock居中到指定的位置
TextBlock text = new TextBlock();
// Some code to define text, font, etc. here
// Turn if Orientation is vertical
if (Orientation == Orientation.Vertical)
{
text.RenderTransform = new RotateTransform() { Angle = 270 };
}
// Update, then ActualWidth is set correctly
text.UpdateLayout();
// Position of label centered to given position
double halfWidth = text.ActualWidth/2;
double x1 = (Orientation == Orientation.Horizontal) ? x - halfWidth : x;
double y1 = (Orientation == Orientation.Horizontal) ? y : y + halfWidth;
Canvas.SetLeft(text, x1);
Canvas.SetTop(text, y1);
Children.Add(text); // Add to Canvas
這工作實際罰款,但有可能做到這一點不UpdateLayout
。如果我刪除UpdateLayout
,那麼我沒有找到我正在尋找的位置,因爲ActualWidth(當然)是零。
你知道,如果你使用一個網格,容器,你要馬上把它居中?除此之外:嘗試使用LayoutTransform而不是RenderTransform – fixagon
父控件是什麼?這段代碼的上下文是什麼? – loxxy
@fantasticfix我必須使用RenderTransform,因爲它在WPF和Silverlight中運行。 SL不知道LayoutTransform。 – Em1