c# - UWP C# 中的居中控件

标签 c# uwp controls

我正在尝试将一个文本 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);
    }

这是生成的应用程序:

the resulting app

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

最佳答案

使用堆栈面板

<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/

相关文章:

cocoa - 类似邮件的带有标记的搜索字段 (Mac OS X 10.7)

具有返回不同类型的子项的抽象类中的 C# 抽象方法

c# - Glimpse 不工作

c# - 如何在 lambda 表达式或 linq 中执行此操作?

c# - 保存加载UWP的文件夹路径

c# - 如何从 Xamarin Forms View 创建 native UWP View ?

c# - 编程通用 Remote

c# - 这两种单例类结构有什么区别?

java - 能否将 Java Swing 桌面应用程序转换为 UWP 百年纪念应用程序 (AppX)?

c# - 从 .NET 的 MFC 列表控件中获取项目