When would ShowDialog() return null?

与世无争的帅哥 提交于 2019-12-01 13:41:03

问题


WPF's Window.ShowDialog method returns a nullable boolean. So does CommonDialog.ShowDialog.

Now, I understand cases where these would return false (user clicked Cancel or pressed Esc), and when they would return true (code sets Window.DialogResult to true, probably in response to OK being clicked). But null?

My first thought is that clicking the title bar's Close button might return null. But the docs state (and I confirmed by testing) that the title-bar Close button is treated as a Cancel.

So when would Window.ShowDialog or CommonDialog.ShowDialog ever return null?


回答1:


The method always returns true or false, and this is always equal to the DialogResult property of the window at the time it closes.

But the DialogResult property is null before the window is closed, and another thread could check the property. So it kind of makes sense that the return value is a nullable boolean to match the property, even though it is never actually null.




回答2:


If I return DialogResult = null in the Click event for a button, the window remains open.

private void OkButton_Click(object sender, RoutedEventArgs e)
{
   Button btn = sender as Button;
   if ( btn != null )
   {
       // forces all control to update...
       btn.Focus();
   }

   // TEST IF OK TO CLOSE
   bool rc = _vm.ProcessOkCommand();
   if (rc)
   {
      DialogResult = true;
   }
   else
   {
      DialogResult = null;
   }
}


<Button Content="OK" Name ="cmdOK" IsDefault="True" Click="OkButton_Click"/>



回答3:


I can give you an example I just encountered. Window.ShowDialog() will return null when you perform the following steps:

  • You first close all of your Application's windows.
  • All other Window objects that have been instantiated up until now with the new keyword are closed.
  • You try to instantiate a new Window and try calling Window.ShowDialog() on it. It will return null.

This is because, presumably, you have no existing Window under which your new dialog can bind to in order to behave like a dialog which owns the topmost window state.



来源:https://stackoverflow.com/questions/990109/when-would-showdialog-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!