Xamarin.Forms.Platform.Gtk handle main window 关闭按钮点击(应用程序退出)

Xamarin.Forms.Platform.Gtk handle main window close button click (application exit)

我有 Xamarin.Forms 应用程序与 GTK 平台实现。 我要做的是在用户关闭主 window 后显示确认警报。警报应询问用户是否要继续并退出应用程序。这在 WPF 平台上很容易,但在 GTK 平台上有困难。

订阅 DeleteEvent 没有帮助。

我的代码是这样的:

[STAThread]
public static void Main(string[] args)
{
    Gtk.Application.Init();
    Forms.Init();
    var app = new App();
    var window = new FormsWindow();
    window.LoadApplication(app);
    window.SetApplicationTitle("Nts");
    window.Show();

    window.DeleteEvent += Window_DeleteEvent; //this is not fired

    Gtk.Application.Run();
}

private static void Window_DeleteEvent(object o, Gtk.DeleteEventArgs args)
{
    //show alert
}

预计单击 "Close" 按钮或应用程序 window 的 Alt + F4 将触发 DeleteEvent 并调用 Window_DeleteEvent 逻辑,但事件未触发且应用程序关闭.

已更新

共享项目: 网络标准 2.0 Xamarin.Forms 版本 4.1.0.618606

GTK 项目: 网络框架 4.8 Xamarin.Forms 版本 4.1.0.618606 Xamarin.Forms.Platform.GTK 版本 3.6.0.344457

事实证明,解决方案非常简单。我所要做的就是继承

Xamarin.Forms.Platform.GTK.FormsWindow 

并覆盖

protected override bool OnDeleteEvent(Event evnt)

像这样

public class MyFormsWindow: FormsWindow
{
  protected override bool OnDeleteEvent(Event evnt)
  {
    var messageDialog = new MessageDialog(Program.MainWindow, DialogFlags.Modal, 
    MessageType.Question, ButtonsType.YesNo,
      "Do you want to exit?", String.Empty)
    {
      Title = "Confirmation",
    };
    int result = messageDialog.Run();

    //the magic numbers stand for "Close" and "No" results
    if (result == -4
      || result == -9
    {
      messageDialog.Destroy();
      return true; // true means not to handle the Delete event by further handlers, as result do not close application
    }
    else
    {
      messageDialog.Destroy();
      return base.OnDeleteEvent(evnt);
    }
  }

当然,要使这项工作正常进行,我们的 Main window 应该具有新的 class.

类型
public class Program
{
public static MyFormsWindow MainWindow { get; private set; }

[STAThread]
public static void Main(string[] args)
{
    Gtk.Application.Init();
    Forms.Init();

    var app = new App();
    var window = new MyFormsWindow();
    window.LoadApplication(app);
    window.SetApplicationTitle("MyApp");
    window.Show();

    MainWindow = window;

    Gtk.Application.Run();
}
}