我正在尝试将一个文本 block 置于我的应用程序窗口的中央。我在文本 block 的 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);
}
这是生成的应用程序:
我是不是做错了什么?是的,这是我在这个线程中唯一的问题。
最佳答案
使用堆栈面板
<Grid>
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Text="Top Text" Margin="20" HorizontalAlignment="Center"/>
<TextBlock Text="Bottom Text" Margin="20" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
关于c# - UWP C# 中的居中控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636996/