0

I have imported the Xaml file into the PowerShell script and opened the window with some text boxes and a button.

On the button click I would like to close that window run some script and then open another window, but I need to be able to do this over and over an infinite number of times until told to stop.

I can open up a new window by naming it window1, but it doesnt open properly and I need to open an "infinite" number of times inside a while loop

[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()

1 Answers1

0

Per this answer (and my experience), WPF Windows cannot be shown again once closed. You have two options:

  1. Keep the same Window instance but change the Visibility to Hidden instead of closing it (as suggested in the answer above). You might need to reset the Window in between uses (e.g. clear text boxes, etc.).
  2. Create a new instance of the Window every time you need to show it.

Either way, you'll need some kind of loop if you want a potentially 'infinite' number of cycles.

If you go with option 2, I'd suggest only reading the XAML from the file once and keeping it in memory, rather than re-reading the file each time you want to create a new Window instance.

Keith Stein
  • 6,235
  • 4
  • 17
  • 36