使用Windows窗体或WPF我可以通过调用ShowDialog打开一个对话窗口。我怎么能用Gtk#?
来做到这一点我尝试制作Window模式,但是虽然它阻止用户与调用窗口进行交互,但它不会等待用户在ShowAll()之后运行代码之前关闭对话框。
答案 0 :(得分:10)
使用Gtk.Dialog而不是使用Gtk.Window,然后调用dialog.Run()。这将返回一个整数值,该值对应于用户用于关闭对话框的按钮的ID。
e.g。
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#中使用Dispose()移动窗口小部件并不会在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。
答案 1 :(得分:0)
我正在尝试创建一个更复杂的对话框,一个没有窗口的对话框 - 它是一个嵌套在滚动视图中的完成树视图的搜索对话框,并使用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。
答案 2 :(得分:0)
我在Gtk.Dialog上实现了以下方法:
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;
}