Wpf – DialogResult WPF

wpf

I am reading one book which says

Rather than setting the DialogResult
by hand after the user clicks a
button, you can designate a button as
the accept button (by setting
IsDefault to true). Clicking that
button automatically sets the
DialogResult of the window to true.
Similarly, you can designate a button
as the cancel button (by setting
IsCancel to true), in which case
clicking it will set the DialogResult
to Cancel.

This is the MainWindow:

<Window x:Class="WpfApplicationWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Width="400" Height="400">
    <StackPanel>

        <Button Name="BtnShowDialogStatus" Click="BtnShowDialogStatus_Click">DIALOG RESULT</Button>
    </StackPanel>
</Window>

Code for click event:

private void BtnShowDialogStatus_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(new NewWindow().ShowDialog().ToString());
}

And this is the Dialog box which I am opening on the click event:

<Window x:Class="WpfApplicationWPF.NewWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="NewWindow" Height="300" Width="300">
    <StackPanel>
        <Button Name="BtnDEfault" IsDefault="True" Click="BtnDEfault_Click">DEFAULT BUTTON</Button>
        <Button Name="BtnCancel" IsCancel="True" Click="BtnCancel_Click">CANCEL BUTTON</Button>
    </StackPanel>
</Window>   

This is the code for it:

private void BtnDEfault_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

I can see it returning the DialogResult only as false no matter I click the default or cancel button.

Best Answer

IsDefault ties the button to the Enter key, so that pressing the Enter key will fire the Click event. It does not mean that the Yes button will return true for the DialogResult.

Refer to the links.It will clear up things for you

http://blog.wpfwonderland.com/2010/03/22/getting-a-dialogresult-from-a-wpf-window/

http://www.wpftutorial.net/Dialogs.html

Hope it helps...