Home > Back-end >  Recenter a window after auto size changed
Recenter a window after auto size changed

Time:01-11

I have a MainDashoard called MainDashView that contains a frame called frViewer, I click a button and it then loads a page called pgEntryView into frViewer.

The page is wider than the frame so when it loads the window width ends up off the screen.

How do I get the MainDashView to recenter or stay fixed to the centre of the screen after the SizeToContent event has fired?

Thanks in advance.

CodePudding user response:

So I have just managed to figure out where I was going wrong.

In order to do this, I need to create the private void CenterWindowOnScreen as follows:

private void CenterWindowOnScreen(object sender, SizeChangedEventArgs e)
        {
            double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
            double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
            double windowWidth = this.Width;
            double windowHeight = this.Height;
            this.Left = (screenWidth / 2) - (windowWidth / 2);
            this.Top = (screenHeight / 2) - (windowHeight / 2);
        }

My mistake came in when I didn't realise that the window was not the only object being resized, the frame was as well, thus by binding their respective SizeChanged properties/events to this method, I am able to always keep the Window at the center of the screen.

  •  Tags:  
  • Related