Monday, 24 July 2017

Using MahApps built-in dialogs with PowerShell


Keeping up with the MahApps.Metro theme, this time I’ll show you how to use the built in Dialog with our WPF window.
When you are looking at the guidelines on the MahApps website they explained how to use asynchronous dialogs (Message Dialog, progress dialog …) with async/await.

Unfortunately, it isn’t available in PowerShell because the UI is using the main thread and managing another thread in PowerShell like other programming language is a little bit frustrating.

I struggled to find a way to make it work with runspacepool and other stuff … but in vain. I was about to stop this project and then I found this.



They made an update in the latest release (1.5.0). New methods are available and we can use them with PowerShell.

These are the two types of dialogs available:
-  internal dialogs
 external dialogs

All the async methods are internal dialogs. Technically you can use them but you cannot get the result. You can try it if you want and test your code with the ShowMessageAsync() method.

External dialogs are a bit different. The UI synchronously waits for the dialog before proceeding, so we can get the result.

All dialogs are available in a Class DialogManager:
[MahApps.Metro.Controls.Dialogs.DialogManager

How do we use it?


First, find the button or the control on which you want to attach the event.
I added a textbox in which I store the result.

$btnOpenDialg      = $ExternalXaml.FindName("btnOpenDialg"
# TextBox for result
$dialgResult       = $ExternalXaml.FindName("dialgResult"

There is nothing to do in the xaml file, everything is managed in the script. I chose to use the “OK/cancel” example because this is the most popular used by people 😊.

The next step is to add the action when a click event occurs.



So to show the message, you call the method inside the dialogManager Class, and that’s it. There’s three mandatory parameters though:
$Form (Your main Form), title and message(otherwise there’s no meaning to it). At least like below then

[MahApps.Metro.Controls.Dialogs.DialogManager]::ShowModalMessageExternal($Form,"Title","Your message. ")

And that’s all. Now you can say goodbye to the old MessageBox and use this new one. 😊

Where to download?


I made a complete project here, with the hamburger menu if you want to download.



Share:

1 comment:

  1. I know this is over a year old now...... But you sir, are amazing. Thank you!

    ReplyDelete

Popular Posts

Join us on Facebook

STATS

Contact Form

Name

Email *

Message *