代码之家  ›  专栏  ›  技术社区  ›  weiqure

是否有与GTK Windows等效的Form.ShowDialog?

  •  2
  • weiqure  · 技术社区  · 16 年前

    使用Windows窗体或WPF,我可以通过调用ShowDialog打开对话框窗口。如何使用GTK?

    我试着让窗口模式化,但是尽管它阻止用户与调用窗口交互,但它不会等待用户在ShowAll()之后运行代码之前关闭对话框。

    3 回复  |  直到 7 年前
        1
  •  10
  •   Mikayla Hutchinson    16 年前

    不要使用gtk.窗口,而是使用 Gtk.Dialog ,然后调用Dialog.Run()。这将返回与用户用于关闭对话框的按钮的ID相对应的整数值。

    例如

    Dialog dialog = null;
    ResponseType response = ResponseType.None;
    
    try {
        dialog = new Dialog (
            "Dialog Title",
            parentWindow,
            DialogFlags.DestroyWithParent | DialogFlags.Modal,
            "Overwrite file", ResponseType.Yes,
           "Cancel", ResponseType.No
        );
        dialog.VBox.Add (new Label ("Dialog contents"));
        dialog.ShowAll ();
    
        response = (ResponseType) dialog.Run ();
    } finally {
        if (dialog != null)
            dialog.Destroy ();
    }
    
    if (response == ResponseType.Yes)
        OverwriteFile ();
    

    请注意,在GTK中处置一个小部件并不会在GTK中销毁它——这是一个历史设计事故,为了向后兼容而保留。但是,如果使用自定义对话框子类,则可以重写Dispose来销毁对话框。如果在构造函数中还添加了子部件和showall()调用,则可以编写更好的代码,如下所示:

    ResponseType response = ResponseType.None;
    using (var dlg = new YesNoDialog ("Title", "Question", "Yes Button", "No Button"))
        response = (ResponseType) dialog.Run ();
    
    if (response == ResponseType.Yes)
            OverwriteFile ();
    

    当然,您可以更进一步,编写一个相当于ShowDialog的代码。

        2
  •  0
  •   Barry Kelly    12 年前

    我试图创建一个更复杂的对话框,一个没有窗口的对话框-它是一个搜索对话框,有一个嵌套在滚动视图中的完成树视图,用Enter或Escape关闭。

    以下是我如何计算您手动组合模式对话框的机制:

    • 在对话框上定义一个属性,该属性指示对话框是否已完成。我打电话给我的 ModalResult ,具有值的枚举 None , OK Cancel .

    • 确保对话框的父窗口在手边( dialogParent 以下)

    样例代码:

    // assuming Dispose properly written per @mhutch
    using (window = new MyDialogWindow()) 
    {
        window.TransientFor = dialogParent;
        window.Modal = true;
        window.Show();
        while (window.ModalResult == ModalResult.None)
            Application.RunIteration(true);
        // now switch on value of modal result
     }
    

    然而注意 this Ubuntu bug with overlay scrollbars . 我不使用它们,我的应用程序是个人使用的,但是YMMV。

        3
  •  0
  •   Michael Rupp    7 年前

    我在gtk.对话框上实现了以下方法:

    public ResponseType ShowDialog()
    {
      List<ResponseType> responseTypes = new List<ResponseType>
      {
        // list all the ResponseTypes that you have buttons for
        // or that you call this.Respond(...) with
        ResponseType.Ok,
        ResponseType.Cancel
      };
    
      this.Modal = true;
    
      // start with any ResponseType that isn't contained in responseTypes
      ResponseType response = ResponseType.None;
    
      while (!responseTypes.Contains(response))
      {
        response = (ResponseType)this.Run();
      }
      this.Destroy();
      return response;
    }