【问题标题】:How to open WPF window multiple times in PowerShell script如何在 PowerShell 脚本中多次打开 WPF 窗口
【发布时间】:2021-11-17 22:57:45
【问题描述】:

我已将 Xaml 文件导入到 PowerShell 脚本中,并打开了带有一些文本框和按钮的窗口。

在按钮单击时,我想关闭该窗口,运行一些脚本,然后打开另一个窗口,但我需要能够一遍又一遍地执行此操作,直到被告知停止。

我可以通过将其命名为 window1 来打开一个新窗口,但它无法正常打开,我需要在 while 循环内打开“无限”次

[System.Reflection.Assembly]::LoadWithPartialName("PresentationFramework") | Out-Null

function Import-Xaml {
    [xml]$xaml = Get-Content -Path "C:\Users\Test\WpfWindow1.xaml"
    $manager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xaml.NameTable
    $manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
    $xamlReader = New-Object System.Xml.XmlNodeReader $xaml
    [Windows.Markup.XamlReader]::Load($xamlReader)
}

$window = Import-Xaml
$window1 = Import-Xaml
$Button = $window.FindName("Button")

$Button.Add_Click({  
    $window.Close()   
})

$window.ShowDialog()

#Run Code

$window1.ShowDialog()

【问题讨论】:

    标签: wpf visual-studio powershell


    【解决方案1】:

    根据this answer(和我的经验),WPF Windows 一旦关闭就无法再次显示。你有两个选择:

    1. 保持相同的Window 实例,但将Visibility 更改为Hidden 而不是关闭它(如上述答案中所建议的那样)。您可能需要在两次使用之间重置Window(例如,明文框等)。
    2. 每次需要显示 Window 时创建一个新实例。

    无论哪种方式,如果您想要潜在的“无限”循环次数,您将需要某种循环。

    如果您选择选项 2,我建议您只从文件中读取一次 XAML 并将其保存在内存中,而不是每次您想创建一个新的 Window 实例时重新读取该文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      相关资源
      最近更新 更多