2009-06-13 117 views
2

使用Windows窗体或WPF我可以通过调用的ShowDialog打开一个对话框窗口。我如何使用Gtk#来做到这一点?是否有与Gtk#Windows等价的Form.Showdialog?

我尝试了使该窗口模式,但尽管它阻止用户与呼叫窗口交互它不会等待用户勾住ShowAll后运行的代码之前关闭对话框()。

回答

10

代替使用Gtk.Window的,使用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(); 

注意的Dispose()荷兰国际集团在GTK#小部件不GTK#destroy()方法是 - 历史设计的事故,保持向后兼容性。但是,如果使用自定义对话框子类,则可以重写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的等效。

+0

需要注意的是在自定义对话框覆盖`Dispose`时,一个具有前*`base.Dispose`调用`Destroy` *很重要 – 2014-12-24 17:22:40

0

我试图创建一个更复杂的对话,一个没有窗户 - 这是与嵌套在一个滚动视图完成树形搜索对话框,并与输入或逃避关闭。

下面是我已经想通你放在一起手动模式对话框的机制:

  • 定义,表示它是否完成没有你的对话框上的属性。我打电话给我的ModalResult,其值NoneOKCancel枚举。

  • 确保您有得心应手的对话框的父窗口(如下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。