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.
The DialogResult
property is defined on the Window
class. Not all Window
s 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
.