WPF:使用模态对话框/ InputDialog查询用户

Ing*_*als 2 wpf modal-dialog textinput

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

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

Jon*_*Jon 7

在WPF中显示模式对话框时,您无需做任何特殊操作.只需Window在项目中添加一个(假设类名为MyDialog),然后执行:

var dialog = new MyDialog();
dialog.ShowDialog();
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中的某个地方:

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
}
Run Code Online (Sandbox Code Playgroud)