取消按钮关闭窗口

本文关键字:窗口 按钮 取消 | 更新日期: 2023-09-27 18:02:32

谢谢你看我的帖子。

我正在尝试插入一个取消按钮,它基本上为窗口做X按钮。

下面的代码来自如何使取消按钮像"x"一样工作按钮?。我有完全相同的情况

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
    }
}
这里是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>

然而,我遵循该线程中的解决方案,并将按钮的IsCancel设置为true,但是仍然没有Cancel()方法可用于我的按钮。

我想知道我错过了什么吗?或者如何让取消按钮像X按钮一样工作。非常感谢。

取消按钮关闭窗口

Button.IsCancel属性不会自动关闭窗口。它所做的就是允许你使用Escape来"按"下按钮。为了关闭窗口,您仍然需要在单击事件处理程序中调用Close()

因此,该事件没有Cancel属性。如果不想关闭窗口,就不要调用Close()