我试图在我的应用窗口中居中文本块。我在文本块的Loaded事件处理程序中尝试了这段代码:
private void textBlock1_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("textBlock1_Loaded");
double textBlockWidth = textBlock1.Width;
double textBlockHeight = textBlock1.Height;
double gridWidth = grid1.Width;
double gridHeight = grid1.Height;
double leftRightMargin_center = (gridWidth - textBlockWidth) / 2;
double topBottomMargin_center = (gridHeight - textBlockHeight) / 2;
double topMargin_needed = topBottomMargin_center - 25;
double bottomMargin_needed = topBottomMargin_center + 25;
double leftMargin_needed = leftRightMargin_center;
double rightMargin_needed = leftRightMargin_center;
textBlock1.Margin = new Thickness(leftMargin_needed, topMargin_needed, rightMargin_needed, leftMargin_needed);
}
以下是生成的应用:
我在这里做错了吗?是的,那是我在这个帖子中唯一的问题。