1

I have an WPF app (.NET Framework 4.8) that has only two windows and no code except for code behind.

Here's the main window XAML:

<Window x:Class="WpfApp3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" SizeToContent="WidthAndHeight">
    <Button Click="ButtonBase_OnClick" Content="Click here" FontSize="100"/>
</Window>

Here's the code behind:

using System.Windows;
namespace WpfApp3
{
    public partial class MainWindow 
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            new Window1 {Left = this.Left + this.Width, Top = this.Top}.Show();
        }
    }
}

The second form, Window1, has just one text block with no real code behind:

<Window x:Class="WpfApp3.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        SizeToContent="WidthAndHeight">
    <TextBlock Text="New form" FontSize="50"/>
</Window>
namespace WpfApp3
{
    public partial class Window1 
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
}

I expect that clicking the button should position Window1 to the right of MainWindow, with no overlap or gap between those two (because Left = this.Left + this.Width).

Why do I always get a visible gap between them? enter image description here

The gap is a result of using MainWindow's width. Left = this.Left makes Window1's and MainWindow's left borders' positions match perfectly.

If I try putting Window1 immediately under MainWindow by writing Top = this.Top + this.Height, a similar (but slightly narrower) gap shows up between the MainWindow's botton and Window1's top.

  • 2
    https://stackoverflow.com/questions/35529885/how-to-create-wpf-window-with-exact-pixel-size – ASh Dec 03 '20 at 11:25
  • 1
    @Vladislav Andreev: Try to define the left position as described in reference provided by @ASh. But, because of your `MainWindow` has vertical borders on right side and `Window1` has left border then multiply by 2: `Left = this.Left + this.Width - SystemParameters.ResizeFrameVerticalBorderWidth*2 - SystemParameters.FixedFrameVerticalBorderWidth*2,` – Jackdaw Dec 03 '20 at 13:08
  • Thanks @ASh and @Jackdaw, what ultimately worked for me was `Left = this.Left + this.Width - (SystemParameters.FixedFrameVerticalBorderWidth + SystemParameters.ResizeFrameVerticalBorderWidth) * 2 - SystemParameters.WindowNonClientFrameThickness.Left`. Still have no idea if that's just a coincidence (`WindowNonClientFrameThickness.Left` and `ResizeFrameVerticalBorderWidth` are equal on my machine) or the correct approach. – Vladislav Andreev Dec 04 '20 at 19:50

0 Answers0