PowerShell WPF弹出窗口行为

b0zn9rqh  于 2023-10-22  发布在  Shell
关注(0)|答案(1)|浏览(125)

我有一个PowerShell WPF XAML脚本。我需要打开弹出窗口,然后更新它的文本。问题是,弹出窗口只在函数结束时打开,而在开始时,即使我指定打开弹出窗口。是否可以先打开弹出窗口,然后更新它,或者它只是行为或弹出,不能改变它?
测试代码:

# Function to get output and
function Test-Popup {
    # $output = Get-Content ".\output.txt" # Test output file
    # return $output
}
[xml]$XAML = @"
<Window Name="wpfWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Width="342"
        Height="267"
        Background="White"
        Title="WPF Window"
        Topmost="True"
        WindowStartupLocation="CenterScreen"
        WindowStyle="ToolWindow">
  <Grid Name="Main_Window" Background="White">
  <Popup Name="Loading_PopUp" Placement="Center" IsOpen="False" Width="300" Height="250">
            <Grid Background="LightGray">
                <Label Width="290" HorizontalAlignment="Center" Margin="0,10,0,0">
                    <TextBlock Name="install_info" TextWrapping="Wrap"/>
                </Label>
            </Grid>
        </Popup>
        <Button Name="Install" Content="Install" HorizontalAlignment="Left" Margin="10,10,0,10" VerticalAlignment="Top" Width="104" Height="23"/>
  </Grid>
</Window>
"@
[Void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
try {

    $XMLReader = (New-Object System.Xml.XmlNodeReader $XAML)
    $XMLForm = [Windows.Markup.XamlReader]::Load($XMLReader)
} 
catch {
    Write-Error "Error building Xaml data.`n$_"
    exit
}
$Xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $XMLForm.FindName($_.Name) -Scope Script }
$install.add_Click({
    $Loading_PopUp.IsOpen = $true
    Start-Sleep 5
    $Message = Test-Popup
    $install_info.AddText($Message)
    })

$XMLForm.ShowDialog() | 
Out-Null

我知道我可以使用PowerShell表单,它可以按照我想要的方式工作,我可以使用第二个XAML。但是可以使用弹出窗口吗?

iszxjhcz

iszxjhcz1#

Start-Sleep阻塞UI线程。
你必须在另一个线程上执行长时间运行的操作,或者你可以使用DispatcherTimer来延迟设置文本的操作:

$dispatcherTimer = [System.Windows.Threading.DispatcherTimer]::new()
$dispatcherTimer.Interval = [timespan]::FromSeconds(5)
$dispatcherTimer.Add_Tick( { 
    $Message = Test-Popup
    $install_info.AddText($Message)

    $timer = [System.Windows.Threading.DispatcherTimer]$args[0]
    $timer.Stop();
} )

$install.add_Click({
    $dispatcherTimer.Stop()
    $Loading_PopUp.IsOpen = $true
    $dispatcherTimer.Start()
})

相关问题