1
votes

Hello fellow programmers,

I've made a rather complicated WPF application with data bound datagrids and stuff. Since the content changes dynamically, the window itself resizes as well (as it's supposed to do). I made a function which aligns the window to the center of the primary screen when the size changes, like this:

this.SizeChanged += delegate
   {
       double screenWidth = SystemParameters.PrimaryScreenWidth;
       double screenHeight = SystemParameters.PrimaryScreenHeight;
       double windowWidth = this.Width;
       double windowHeight = this.Height;
       this.Left = ( screenWidth / 2 ) - ( windowWidth / 2 );
       this.Top = ( screenHeight / 2 ) - ( windowHeight / 2 );
   };

It works like I suspected it to. However, since the content is data bound, it takes roughly 1/4th a second before the content is available. The SizeChanged event above already did it's job by that time, so the window is not centered at all.

Can i implement some sort of timeout before the event is triggered without locking everything up?

Awaiting your responses patiently!

1

1 Answers

4
votes

Just a guess but one of these may work

  this.SizeChanged += delegate
  {
      Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)delegate()
      {
          double screenWidth = SystemParameters.PrimaryScreenWidth;
          double screenHeight = SystemParameters.PrimaryScreenHeight;
          double windowWidth = this.Width;
          double windowHeight = this.Height;
          this.Left = (screenWidth / 2) - (windowWidth / 2);
          this.Top = (screenHeight / 2) - (windowHeight / 2);
      });
  };


  this.SizeChanged += delegate
  {
      ThreadPool.QueueUserWorkItem((o) =>
      {
          Thread.Sleep(100); //delay (ms)
          Dispatcher.Invoke(DispatcherPriority.Background, (Action)delegate()
          {
              double screenWidth = SystemParameters.PrimaryScreenWidth;
              double screenHeight = SystemParameters.PrimaryScreenHeight;
              double windowWidth = this.Width;
              double windowHeight = this.Height;
              this.Left = (screenWidth / 2) - (windowWidth / 2);
              this.Top = (screenHeight / 2) - (windowHeight / 2);
          });
      });
  };

Like I said just a guess as I dont have a setup to replicate the data load delay