【问题标题】:WPF: Querying user with Modal Dialog box / InputDialogWPF:使用模态对话框/ InputDialog查询用户
【发布时间】:2011-06-03 08:49:58
【问题描述】:

在 WPF 应用程序中,我必须从用户那里获取一行信息,并且我不想使用模态对话框。但是,似乎没有为此预设对话框。有什么简单易行的方法来做到这一点。我发现使用许多版本的 Dialogs 等来找出这一点有点复杂。

我已经不得不使用 OpenFileDialog 和 SaveFileDialog。 Microsoft.Win32 和 System.Windows.Form 这样的版本有什么不同?

【问题讨论】:

    标签: wpf modal-dialog textinput


    【解决方案1】:

    在 WPF 中显示模式对话框不需要做任何特别的事情。只需在您的项目中添加一个Window(假设类名是MyDialog),然后执行:

    var dialog = new MyDialog();
    dialog.ShowDialog();
    

    Window.ShowDialog 负责以模态方式显示窗口。

    示例:

    public class MyDialog : Window {
        public MyDialog() {
            this.InitializeComponent();
            this.DialogResult = null;
        }
    
        public string SomeData { get; set; } // bind this to a control in XAML
        public int SomeOtherData { get; set; } // same for this
    
        // Attach this to the click event of your "OK" button
        private void OnOKButtonClicked(object sender, RoutedEventArgs e) {
            this.DialogResult = true;
            this.Close();
        }
    
        // Attach this to the click event of your "Cancel" button
        private void OnCancelButtonClicked(object sender, RoutedEventArgs e) {
            this.DialogResult = false;
            this.Close();
        }
    }
    

    在您的代码中某处:

    var dialog = new MyDialog();
    // If MyDialog has properties that affect its behavior, set them here
    var result = dialog.ShowDialog();
    
    if (result == false) {
        // cancelled
    }
    else if (result == true) {
        // do something with dialog.SomeData here
    }
    

    【讨论】:

    • 一切都很好,但是你如何定义一个inputDialog,你从什么继承等等?
    • @Ingo:你继承自Window。它没有什么特别之处。
    • 我明白了。您可以向我指出如何在 ShowDialog 方法中返回 Bool 以及如何访问输入等的任何教程?
    • @Ingo:添加了一个示例,希望对您有所帮助。
    • 现在我看到它是如此明显。我以前从未使用过 WPF Window 类,所以我不确定您最初在说什么。
    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多