Hello together,
if you work with more complex scripts behind the GUI you will come to a point, where you want to make changes to the GUI appearance within the CodeBehind-file. An example herefore would be the usage of a progressBar. But how can this be done?
Let´s take an example where you want to do a specific job, which takes long time to finish.
$PSGUI_bXAML.Add_Click( { $PSGUI_progressbar1.Visible = $true #Init CancelLoop #Reset the Progress Bar $PSGUI_progressbar1.Value = 0 $PSGUI_progressbar1.Maximum=20 for($i = 0; $i -lt $PSGUI_progressbar1.Maximum; $i++) { Start-Sleep -s 1 $PSGUI_progressbar1.Value++ } $PSGUI_progressbar1.Visible = $False } )
We have a window which is named “PSGUI” and a progressBar named “progressbar1”. On the buttonClick-Event of the button “bXAML” we initialize our progressBar to give the user a visual feedback while we do a specific job for a several time. Herefore we increase the values of the progressBar after each loop. Normally this should work – you think.
But you will run into a problem. If you modify the value of the progressBar or any other object visible in the GUI this would only become visible after the whole execution because it is executed in only one workerthread. To fix this issue we use a simple trick.
We call like a rerender of the window whithin the code block. In this example like this:
$PSGUI_bXAML.Add_Click( { $PSGUI_progressbar1.Visible = $true #Init CancelLoop #Reset the Progress Bar $PSGUI_progressbar1.Value = 0 $PSGUI_progressbar1.Maximum=20 for($i = 0; $i -lt $PSGUI_progressbar1.Maximum; $i++) { Start-Sleep -s 1 $PSGUI_progressbar1.Value++ $PSGUI.Dispatcher.Invoke([action]{},"Render") } $PSGUI_progressbar1.Visible = $False } )
By this Invoke command the GUI will be refreshed at this exact time and you will see a increasing progressBar in the GUI.
Take a closer look at the picture: the sequence is started in the CodeBehind file in the code. Now you make some changes to the GUI – like changing the appearance of some objects or its containing values. Afterwards you force the rerender process with the Invoke-command which executes the GUI-refresh in parallel with the following continuation of the code. And that´s it.
Do not forget, that you have to place the refreshes as rare as possible.
And now – make some interactive dialogs! 🙂
Greetings,
David