UWP C# 中的居中控件

Centering controls in UWP C#

我正试图在我的应用中将文本块居中 window。我在文本块的 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);
    }

这是生成的应用程序:

我是不是做错了什么?是的,这是我在这个话题中唯一的问题。

使用StackPanel

<Grid>
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBlock Text="Top Text" Margin="20" HorizontalAlignment="Center"/>
        <TextBlock Text="Bottom Text" Margin="20" HorizontalAlignment="Center"/>
    </StackPanel>
</Grid>