如何在WPF中使窗口标题居中对齐? [重复]

问题描述 投票:0回答:1

下面的代码使WinForm中的表单标题居中对齐。

private void Form1_Resize(object sender, EventArgs e)
    {
        Graphics g = this.CreateGraphics();
        Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2);
        Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
        String tmp = " ";
        Double tmpWidth = 0;
        while ((tmpWidth + widthOfASpace) < startingPoint)
        {
            tmp += " ";
            tmpWidth += widthOfASpace;
        }
        this.Text = tmp + this.Text.Trim();
    }

您知道上面代码的WPF版本吗?

c# wpf vb.net winforms
1个回答
0
投票

您可以通过在XAML中添加TextBlock.TextAlignment="Center"来获得受限制的窗口标题:

<Window x:Class="YourNamespace.YourWindowClass"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:YourNameSpace"
        mc:Ignorable="d"
        Title="Your center-aligned title"
        TextBlock.TextAlignment="Center"> <!-- here -->
    <Grid></Grid>
</Window>
© www.soinside.com 2019 - 2024. All rights reserved.