Why is DialogResult a nullable bool in WPF?

PeterAllenWebb picture PeterAllenWebb · Jun 12, 2009 · Viewed 8.6k times · Source

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 made a lot more sense to me.

Answer

Kent Boogaart picture Kent Boogaart · Jun 12, 2009

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:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <Button Name="b1">Show</Button>
        <Button Name="b2">ShowDialog</Button>
    </StackPanel>
</Window>

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.