当用户单击 WPF 中的 X 按钮时,如何显示 MessageBox 提示

How do I show a MessageBox promp when the user has clicked the X button in WPF

我正在开发 C# WPF 应用程序。 在我从用户那里得到一些输入后,我需要检查一些条件,如果条件不匹配并且用户按下了 X 按钮,我需要能够显示一个包含错误的 MessageBox。用户在 MessageBox 中按下 ok 后,我需要用户 return 到上一个 window。 我的代码看起来像这样。

  private void Window_Closing(object sender, CancelEventArgs e)
  {
     MessageBoxResult closingMessegeBoxResult = MessageBox.Show("Is it OK to close?", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     if (closingMessegeBoxResult != MessageBoxResult.OK)
     {
        e.Cancel = true;
        this.Activate();
     }
  }
     private void Window_Closed(object sender, EventArgs a)
  {

  }

目前我只想显示带有随机错误的 MessageBox。

您的代码运行正常。

您必须将 OnClosing 事件添加到 window,

当您点击 window 的关闭时,您将看到消息

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestProject"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800"

    Closing="MainWindow_OnClosing">
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainWindow_OnClosing(object? sender, CancelEventArgs e)
    {
        MessageBoxResult closingMessegeBoxResult = MessageBox.Show("Is it OK to close?", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        if (closingMessegeBoxResult == MessageBoxResult.OK)
        {
            e.Cancel = true;
            this.Activate();
        }
    }
}

您应该使用 MessageBoxButton.OKCancel 选项来让用户避免关闭 window:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    MessageBoxResult closingMessegeBoxResult = MessageBox.Show("Is it OK to close?", "Error",
        MessageBoxButton.OKCancel, MessageBoxImage.Error);
    if (closingMessegeBoxResult != MessageBoxResult.OK)
    {
        e.Cancel = true;
    }
}

使用上面的代码,window只有在用户点击对话框的“确定”按钮时才会关闭。