Note that there are some explanatory texts on larger screens.

plurals
  1. POHorizontally Center TextBlock in Fullscreen
    primarykey
    data
    text
    <p>I've got a <strong>WPF Window</strong> that I made fullscreen by assigning the following properties:</p> <pre><code>WindowState = Maximized WindowStyle = None Topmost = true </code></pre> <p>This works very good so far. Now I got two <code>TextBlocks</code> on my <code>Window</code> that I both want to center horizontally. Since it's fullscreen my idea was to just calculate the position from the screen's resolution. So I tried the following:</p> <pre><code>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); } </code></pre> <p><code>WinApi</code> is a class from me that encapsulates <code>WinApi</code>. I'm using <code>ActualWidth</code> since the width of both <code>TextBlocks</code> is set to <code>Auto</code>. Getting the screen's dimensions works fine so far. However the textBlocks are not rendered exactly in the middle of the screen. I know that for sure because they are both rendered at different horizontal positions.</p> <p>My XAML:</p> <pre><code>&lt;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"&gt; &lt;Grid&gt; &lt;TextBlock x:Name="textBlockHeader" HorizontalAlignment="Center" Background="White" Foreground="#FF0C04DB" FontWeight="Bold" FontFamily="Lucida Console" Width="Auto" Height="Auto" Text="Header" TextAlignment="Center"/&gt; &lt;TextBlock x:Name="textBlockText" HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center" FontFamily="Lucida Console" Text="text"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload