【问题标题】:WPF event on disabled window禁用窗口上的 WPF 事件
【发布时间】:2019-07-08 09:53:43
【问题描述】:

是否有可能在禁用的 WPF 窗口上处理事件?主窗口被其他窗口的.ShowDialog() 禁用。在我的应用程序中,一次只启用一个窗口,我想提高可用性。如果用户点击了错误的(禁用的)主窗口,应用程序应该自动聚焦到启用的窗口。

我知道禁用意味着窗口不响应任何事件,但是有没有像全局事件处理程序或一些特殊的 WPF 事件这样的解决方案?

我尝试了PreviewMouseLeftButtonDown 事件,但没有成功。

// event called from some special/ global event on disabled window
private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if(App.Current.Windows.Count > 1)
    {
       foreach(Window w in App.Current.Windows)
       {
           if(w.IsEnabled) 
           {
               w.Focus();
               break;
           }
       }          
    }
}

感谢您的想法/解决方案!

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    调用ShowDialog 表示您想让窗口显示为modal,从而禁用其他窗口。

    将此方法切换为Show,您也可以使用其他窗口。

    请参阅this

    【讨论】:

      【解决方案2】:

      感谢您的提示,但作为一项要求,我必须确保在打开另一个窗口时冻结主窗口并且我找到了解决方案:我已经冻结了所有控件,而不是使用 .ShowDialog() 冻结窗口当使用.Show() 打开一个新窗口时。

      private void DisableAllControls()
      {
          // parallel execution cause of many elements
          Parallel.For(0, VisualTreeHelper.GetChildrenCount(this), index =>
          {
              (VisualTreeHelper.GetChild(this, index)
              as UIElement).IsEnabled = false;
          });
      }
      

      我还添加了一个MouseDownEvent,以便在用户单击“冻结”主窗口时获得新窗口的焦点。 (同时只会打开一个额外的窗口)。

      private void FocusLastOpen_MouseDown(object sender, MouseEventArgs e)
      {
          if (App.Current.Windows.Count > 1)
          {
              foreach (Window w in App.Current.Windows)
              {
                  if (w.IsEnabled && w.GetType() != typeof(MainWindow))
                  {
                      w.Focus();
                  }
              }
          }
      }
      

      为了在另一个窗口关闭时重新激活主窗口的元素,我编写了一个静态方法,该方法将在 ClosingEvent 上执行。

      public static void EnableAllControls()
      {
          MainWindow obj = null;
          foreach(Window w in App.Current.Windows)
          {
              if(w.GetType() == typeof(MainWindow))
              {
                  obj = w as MainWindow;
                  break;
              }
          }
      
          if(obj == null) return;
          Parallel.For(0, VisualTreeHelper.GetChildrenCount(obj), index =>
          {
              (VisualTreeHelper.GetChild(obj, index)
              as UIElement).IsEnabled = true;
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 2010-10-29
        • 2016-10-24
        • 2012-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多