经常会遇到要在Canvas里将各类控件居中的问题,下面以TextBlock为例说明。
//在将TextBlock添加到Canvas前获取它的实际尺寸 TextBlock label = new TextBlock; label.Text = "It is a test"; label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); Size labelSize = label.DesiredSize; Canvas canvas = new Canvas(); canvas.Width = 100; canvas.Height = 40; canvas.Children.Add(label); Canvas.SetLeft(label, (canvas.Width - labelSize.Width)/2); Canvas.SetTop(label, (canvas.Height - labelSize.Height)/2);