0

我有一个WPF 窗口,我通过分配以下属性制作了全屏:

WindowState = Maximized
WindowStyle = None
Topmost = true

到目前为止,这非常有效。现在我有两个TextBlocksWindow都想水平居中。因为它是全屏的,所以我的想法是从屏幕的分辨率计算位置。所以我尝试了以下方法:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    IntPtr handle = WinApi.getWindowByName("myWindow");
    int height = Screen.FromHandle(handle).Bounds.Height;
    int width = Screen.FromHandle(handle).Bounds.Width;
    textBlock1.Margin = new Thickness(width / 2 - textBlock1.ActualWidth, height / 10, width / 2 - textBlock1.ActualWidth, height / 1.5);
    textBlock2.Margin = new Thickness(width / 2 - textBlock2.ActualWidth, height / 10, width / 2 - textBlock2.ActualWidth, height / 3);
}

WinApi是我封装的一个类WinApi。我正在使用ActualWidth,因为两者的宽度都TextBlocks设置为Auto. 到目前为止,获取屏幕的尺寸工作正常。然而,textBlocks 并没有完全呈现在屏幕的中间。我肯定知道,因为它们都呈现在不同的水平位置。

我的 XAML:

<Window x:Class="MyApp.MyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="test" Height="300" Width="300" WindowState="Maximized" WindowStyle="None" Topmost="True" Background="#FF0000DC" Foreground="#FFF4FCF8" Loaded="Window_Loaded">

    <Grid>
        <TextBlock x:Name="textBlockHeader" HorizontalAlignment="Center" Background="White" Foreground="#FF0C04DB" FontWeight="Bold" FontFamily="Lucida Console" Width="Auto" Height="Auto" Text="Header" TextAlignment="Center"/>
        <TextBlock x:Name="textBlockText" HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center" FontFamily="Lucida Console" Text="text"/>
    </Grid>
</Window>
4

2 回答 2

0

你在逆流而上。为什么不直接使用 WPF 的布局系统

<Window ...>
    <StackPanel>
        <TextBlock HorizontalAlignment="Center">Foo</TextBlock>
        <TextBlock HorizontalAlignment="Center">Bar</TextBlock>
    </StackPanel>
</Window>

看到你的截图后更新:

你的 XAML 一定有问题,但我不能说是什么,因为你还没有发布它。这对我来说非常有效:

<Window x:Class="SO16881549.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        WindowState="Maximized"
        WindowStyle="None"
        Topmost="True">
    <DockPanel>
        <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Center">Title</TextBlock>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">This is a test-text!</TextBlock>
    </DockPanel>
</Window>
于 2013-06-02T09:45:15.563 回答
0

尝试这个:

<TextBlock Text="Your text" HorizontalAlignment="Center" VerticalAlignment="Center" />
于 2013-06-02T09:47:27.723 回答