开发者

WPF: Querying user with Modal Dialog box / InputDialog

In a WPF application I have to get one line of info from user and I wan't to use a Modal Dialog. However there seems to be no preset dialog for this. What's a simple and easy way to do this. I find it somwhat complicated trying 开发者_C百科to find this out with the many versions of Dialogs and such.

Already I have had to use OpenFileDialog and SaveFileDialog. What is the different between version of these like Microsoft.Win32 and System.Windows.Form ?


There's nothing special you need to do to show a modal dialog in WPF. Just add a Window to your project (let's say the class name is MyDialog), and then do:

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

Window.ShowDialog takes care of showing the window in a modal manner.

Example:

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();
    }
}

In your code somewhere:

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜