Why is DialogResult a nullable bool in WPF?

后端 未结 5 675
逝去的感伤
逝去的感伤 2021-01-17 08:59

Can anyone think of a good explanation for the fact that result of a dialog is a nullable bool in WPF? This has always baffled me. In WinForms it was an enum type and that m

5条回答
  •  一生所求
    2021-01-17 09:18

    The DialogResult property is defined on the Window class. Not all Windows are dialogs. Therefore, the property isn't relevant to all windows. A Window that has been shown via Show() rather than ShowDialog() will (presumably, unless you set it for some reason) have DialogResult = null.

    Here's a simple example to demonstrate:

    Window1.xaml:

    
        
            
            
        
    
    

    Window1.xaml.cs:

    using System.Windows;
    
    namespace WpfApplication1
    {
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                b1.Click += new RoutedEventHandler(b1_Click);
                b2.Click += new RoutedEventHandler(b2_Click);
            }
    
            void b1_Click(object sender, RoutedEventArgs e)
            {
                var w = new Window();
                w.Closed += delegate
                {
                    MessageBox.Show("" + w.DialogResult);
                };
    
                w.Show();
            }
    
            void b2_Click(object sender, RoutedEventArgs e)
            {
                var w = new Window();
                w.ShowDialog();
                MessageBox.Show("" + w.DialogResult);
            }
        }
    }
    

    When you close the windows, you'll notice that the dialog has a DialogResult of false, whilst the non-dialog has a null DialogResult.

提交回复
热议问题