在全屏中水平居中TextBlock

时间:2013-06-02 09:40:58

标签: c# .net wpf fullscreen center

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

WindowState = Maximized
WindowStyle = None
Topmost = true

到目前为止这项工作非常好。现在我的TextBlocks上有两个Window,我想要水平居中。因为它是全屏我的想法是从屏幕的分辨率计算位置。所以我尝试了以下内容:

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>

2 个答案:

答案 0 :(得分:0)

你在上游游泳。为什么不使用WPF的layout system

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

答案 1 :(得分:0)

试试这个:

<TextBlock Text="Your text" HorizontalAlignment="Center" VerticalAlignment="Center" />
相关问题