We have created the basics for the MessageBox dialog in Part I and Part II. One thing that we realized is that there is no way to block on MessageBox.Show. The cleanest solution to get the dialog result is to make our call API "asynchronous".
Something like this:
public delegate void DialogCloseDelegate(
object sender,
DialogResult dialogResult);
public static class MessageBox {
public static void Show(string title, string text, DialogStyle dialogStyle,
DialogCloseDelegate callback) {
InternalShow(title, text, dialogStyle, callback);
}
}
...
public class MessageBoxControl : ContentControl {
DialogCloseDelegate _callback;
public MessageBoxControl(Popup owner, DialogCloseDelegate callback)
: this() {
this._callback = callback;
...
}
void DialogButtonClick(object sender, RoutedEventArgs e) {
DialogButton button = sender as DialogButton;
if (this._owner != null && button != null) {
this._owner.IsOpen = false;
if (_callback != null) {
_callback(this, button.DialogResult);
}
}
}
}
We can then use the MessageBox like so:
private void Button_Click(object sender, RoutedEventArgs e) {
MessageBox.Show("Title", "Hello World", DialogStyle.OkAndCancel,
new DialogCloseDelegate(OnDialogClose));
}
void OnDialogClose(object sender, DialogResult dialogResult) {
MessageBox.Show("Dialog Result", dialogResult.ToString());
}
What's Next?
Since this is just demo code, a lot of things have been simplified. For example you might want to move the hard-coded "OK" and "Cancel" button contents out into properties. You could make the default template for the message box surface a little prettier, so that it has the look and feel of your application. Hopefully, this article will get you started.
Download the Source Code
Cheers,
Azret