[英]How do I make a Powershell WPF form run a function when loaded (and display itself)?
我在 Powershell 中有一个登录脚本,我使用的是 WPF 表单。 我希望它加载一个表单,然后使用脚本进度更新表单。
我在用:
$Window.Add_Loaded({
DoStuff
})
但是,发生的情况是脚本运行,然后在完成后加载表单。
如果我在表单上放一个按钮来触发脚本函数,表单将加载,然后按预期更新,即:
$Button.Add_Click({
DoStuff
})
一个简化的例子如下:
Add-Type -AssemblyName presentationframework
[xml]$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window" Title="Countdown" WindowStartupLocation="CenterScreen" WindowStyle="None" Background="#2C2A6F" ResizeMode="NoResize" Width="100" Height="140">
<StackPanel>
<Label Content="3" x:Name="Counter" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontWeight="Bold" FontSize="90" Padding="0,0,0,0" />
<Button Content="Go" x:Name="Button" />
</StackPanel>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$Counter = $Window.FindName("Counter")
$Button = $Window.FindName("Button")
$Button.Add_Click({
Countdown
})
$Window.Add_Loaded({
})
Function Countdown(){
for($i=3; $i-ge 0; $i--) {
$Counter.Content = $i
$Window.Dispatcher.Invoke([Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle);
Start-sleep -Seconds 1
}
}
$Window.ShowDialog()
这在加载表单时起作用,然后当我单击按钮时,它会倒计时到零。 但是,如果我将其更改为:
$Window.Add_Loaded({
Countdown
})
该脚本以尚未可见的表单运行,然后将计数器显示为零。
如何设置它以便显示表单,然后触发该功能以自动开始倒计时?
当整个窗口准备就绪时,会触发 Loaded 事件。 渲染前的最后一站。
这对你的Countdown
有点太早了。
使用 ContentRendered 事件。
$Window.Add_ContentRendered({
Countdown
})
这是一个很好的参考WPF 应用程序的生命周期事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.