Skip to content

Instantly share code, notes, and snippets.

@killnine
Last active August 29, 2015 14:05
Show Gist options
  • Save killnine/35a26264b2ead577e045 to your computer and use it in GitHub Desktop.
Save killnine/35a26264b2ead577e045 to your computer and use it in GitHub Desktop.
DialogBehavior for MahApps.Metro MessageBox
public class DialogBehavior : Behavior<MetroWindow>
{
public MetroWindow Window { get; set; }
protected override void OnAttached()
{
base.OnAttached();
Window = base.AssociatedObject;
//Here you'd use Caliburn's EventBus or whatever...
Messenger.Default.Register<DialogMessageAction<string>>(this, DialogMessageToken.InputDialog, DisplayInputDialog);
Messenger.Default.Register<NotificationMessage>(this, DialogMessageToken.ErrorDialog, DisplayErrorDialog);
Messenger.Default.Register<DialogMessageAction<string>>(this, DialogMessageToken.ProgressDialog, async action => await DisplayProgressDialog(action));
}
private void DisplayInputDialog(DialogMessageAction<string> m)
{
Window.ShowInputAsync(m.DialogTitle, m.Notification, new MetroDialogSettings{ DefaultText = m.DefaultMessage }).ContinueWith(result =>
{
if (result.Result == null) //user cancelled
{
return;
}
m.Execute(result.Result);
});
}
private async Task DisplayProgressDialog(DialogMessageAction<string> m)
{
var controller = await Window.ShowProgressAsync(m.DialogTitle, m.Notification);
await TaskEx.Delay(5000);
double i = 0.0;
while (i < 6.0)
{
double val = ((double)(i/100.0))*20.0;
controller.SetProgress(val);
controller.SetMessage("Completing Task..." + (val*100) + " percent complete.");
i += 1.0;
await TaskEx.Delay(2000);
}
await controller.CloseAsync();
}
private void DisplayErrorDialog(NotificationMessage m)
{
Window.ShowMessageAsync("Error", m.Notification).ContinueWith(result => { });
}
protected override void OnDetaching()
{
Messenger.Default.Unregister(this);
}
}
public class DialogMessageAction<T> : NotificationMessageWithCallback
{
public string DialogTitle { get; set; }
public string DefaultMessage { get; set; }
public DialogMessageAction(string notification, string dialogTitle, string defaultMessage, Action<T> callback) : base(notification, callback)
{
DialogTitle = dialogTitle;
DefaultMessage = defaultMessage;
}
}
<!-- Then just add this to your ModernWindow -->
<i:Interaction.Behaviors>
<behaviors:DialogBehavior/>
</i:Interaction.Behaviors>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment