Ono
Ono

Reputation: 1357

Cancel button closing window

Thanks for reading my thread.

I am trying to insert a cancel button that basically does the X button for a window.

Here is the code from How would I make a cancel button work like the "X" button?. I have exactly the same situation

public partial class Dialog : Window
{
    .
    .
    .

    private void Window_Closing(object sender, CancelEventArgs e)
    { 
        e.Cancel() = true; //Works as expected
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        e.Cancel() = true; //Compile error
    }
}

Here is the xaml:

<Window x:Class="ExperimentSettingsViewer.TemplateName"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Template Name"
        Height="120"
        Width="300"
        WindowStartupLocation="CenterOwner">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ExperimentSettingsViewer;component/Button.xaml" />
                <ResourceDictionary Source="/ExperimentSettingsViewer;component/Window.xaml" />
                <ResourceDictionary Source="/ExperimentSettingsViewer;component/Border.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <TextBox Name="tbName"
                     Margin="3"
                     Text="{Binding Path=NewName}" />
            <StackPanel Orientation="Horizontal" HorizontalAlignment="right">
                <Button Name="btnOK"
                    Content="OK"
                    Width="75"
                    Height="30"
                    HorizontalAlignment="Right"
                    Margin="3"
                    Click="btnOK_Click" />
                <Button Name="btnCancel"
                    Content="Cancel"
                    Width="75"
                    Height="30"
                    HorizontalAlignment="Right"
                    Margin="3"
                    Click="btnCancel_Click" IsCancel="True" />
            </StackPanel>

        </StackPanel>
    </Grid>
</Window>

However, I follow the solution in that thread, and set the IsCancel of the buttom to true, but still, there is no Cancel() methods available for my button.

I am wondering is there anything I missed? Or how can I make my cancel button work like a X button. Thanks a lot.

Upvotes: 0

Views: 193

Answers (1)

Nathan A
Nathan A

Reputation: 11319

The Button.IsCancel property does not automatically close your window. All it does is allow you to use Escape to "press" the button. You still need to call Close() in your click event handler in order to close the window.

Because of this, there is no Cancel property for that event. If you don't want to close the window, just don't call Close().

Upvotes: 4

Related Questions