在WPF应用程序中,我必须从用户那里获得一行信息,我不想使用模态对话框。但是,似乎没有预设对话框。什么是简单易行的方法。我发现用多种版本的Dialogs等来解决这个问题真是太复杂了。
我已经不得不使用OpenFileDialog和SaveFileDialog。这些版本之间有什么不同,如Microsoft.Win32和System.Windows.Form?
答案 0 :(得分:7)
在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
}