我有一个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>