WPF which event to choose ?

Hi everyone,

my goal is to start a process when the GUI is open and see the progress bar growing.

The process work fine, but I only see the render at the end of the process and not during the process.

I’ve tried to change the event (Activated/ContentRendered/Initialized/Loaded) but I still not have the correct result.

Or maybe there is another way to do it ?

[pre]

add-type -AssemblyName PresentationFramework
[xml]$FormoutFile = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="MainWindow" Height="450" Width="800">
<Canvas HorizontalAlignment="Left" VerticalAlignment="Top" >
<ProgressBar Name="PB" Height="20" Canvas.Left="0" Canvas.Top="0" Width="792"/>
<TextBlock Name="TB_Text" Canvas.Left="0" TextWrapping="Wrap" Canvas.Top="21" Height="370" Width="792" Text="TextBlock"/>
<Button Name="BT_Close" Content="Close" Canvas.Left="0" Canvas.Top="391" Width="75" Height="20" />
</Canvas>
</Window>
"@
$NR = (New-Object System.Xml.XmlNodeReader $FormoutFile)
$Formout = [Windows.Markup.XamlReader]::load($NR)
$ProgessBar = $Formout.findName("PB")
$TextOut = $Formout.findName("TB_Text")
$BT_Close = $Formout.findName("BT_Close")
$Formout.Add_Loaded({
$BT_Close.isEnabled=$false
$Progress=0
$ProgessBar.value=$Progress
$TextOut.text=@("START`n")
For ($i=0;$i-lt10;$i++){
start-sleep1
$TextOut.text+=@("Step $i`n")
$Progress+=$i*10
$ProgessBar.value=$Progress
}
$TextOut.text+=@("END")
$BT_Close.isEnabled=$true
})
$BT_Close.Add_Click({
$Formout.close()
})
$Formout.showdialog()
[/pre]

The reason for seeing the progress at the end is because the script you are showing is single threaded. Essentially, it can’t do the work and show the work at the same time.

I’ve spent a lot of time doing multi-threaded windows at this point, but I got it started from this blog series, https://foxdeploy.com/2016/05/17/part-v-powershell-guis-responsive-apps-with-progress-bars/.

Stephen Owen does a really good job of showing how this exact thing is done.

Happy Coding!

Many thanks,

I learn new stuff every days on Powershell, 5 days ago I don’t know WPF, now I’m going to do multi thread.

Going back to my code :wink: