我是WPF和使用PowerShell進行事件處理的新手,我想實現的是點擊一個按鈕,進度條應該顯示在0-100之間。但是,當我運行以下代碼段時,它會計算add_click塊內的整個代碼,並且它僅顯示循環中的最後一次迭代。 我知道也許這是一個愚蠢的解決方案,但我確實需要一些幫助。
$syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
$psCmd = [PowerShell]::Create().AddScript({
$XamlPath="C:\Forms\MyFormsv1.xaml"
$inputXML = Get-Content -Path $XamlPath
[xml]$Global:xmlWPF = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^<Win.*', '<Window'
#Add WPF and Windows Forms assemblies
try{
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
} catch {
Throw 「Failed to load Windows Presentation Framework assemblies.」
}
$syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))
[xml]$XAML = $xmlWPF
$xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
$Global:synchash.Add($_.Name,$synchash.Window.FindName($_.Name))}
function tool1_progress{
$var1=50
for($index=1 ; $index -le $var1; $index++)
{
[int]$tmpProgNum= ($index/$var1) * 100
$syncHash.tool1_pb.Value= $tmpProgNum
$syncHash.consoleOutput.Text=$index
Start-Sleep -Milliseconds 250
}
}
$syncHash.myButton.add_click({tool1_progress})
$syncHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()
$工具1是一個標籤。 $ tool1_pb是一個進度條。 $ consoleOutput是一個 文本框。
你的代碼的功能禮貌,更新,這意味着當你的循環執行的UI不能更新UI中的同一個線程上運行。 – mm8
是的,我知道必須有某種線程問題,你能否爲我提供解決方案來解決這個問題。謝謝您的好意。 :) –
您需要使用'BeginInvoke()'創建一個新的運行空間。當我試圖和你一樣做同樣的事時,這幫助了我。 https://learn-powershell.net/2012/10/14/powershell-and-wpf-writing-data-to-a-ui-from-a-different-runspace/ – Nick