1

各位程序员好,

我用数据绑定的数据网格和东西制作了一个相当复杂的 WPF 应用程序。由于内容会动态变化,因此窗口本身也会调整大小(正如它应该做的那样)。我做了一个功能,当尺寸改变时,窗口与主屏幕的中心对齐,如下所示:

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 );
   };

它就像我怀疑的那样工作。但是,由于内容是数据绑定的,因此内容可用大约需要 1/4 秒。到那时,上面的 SizeChanged 事件已经完成了它的工作,所以窗口根本没有居中。

我可以在触发事件之前实现某种超时而不锁定所有内容吗?

耐心等待您的回复!

4

1 回答 1

4

只是一个猜测,但其中一个可能有效

  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);
          });
      });
  };

就像我说的只是猜测,因为我没有设置来复制数据加载延迟

于 2012-12-03T09:45:42.880 回答