简体   繁体   中英

How to call a method of a WPF form element running in another runspace in Powershell

I'm playing around with using runspaces in PowerShell to enhance performance of a small GUI application.

What I've got so far is a runspace that has 2 purposes: First, it holds all my other runspaces and second, it parses my GUI xml file and displays it. It also adds the nodes to a sychronized hashtable, so I have it accessible across all runspaces. As you can imagine I have some buttons in this GUI which trigger actions when clicked; pretty simple stuff and actually it's working great so far. I can exchange data between the runspaces and I am also able to update the GUI when a certain button is clicked.

However, I am not able to call the addChild() method on an empty stackpanel in my xml file. What I basically want to do is just to add checkboxes to the stackpanel (named "CheckboxViewer").

$checkbox = New-Object System.Windows.Controls.CheckBox
$checkbox.Content = "Hello world"
$syncHash.checkbox = $checkbox
$syncHash.CheckboxViewer.Dispatcher.Invoke(
     [Action]{
         #this is working:
         $syncHash.CheckboxViewer.Background = 'Black'
         #this is not working
         $syncHash.CheckboxViewer.AddChild($syncHash.checkbox)
     }, "Normal")

The error message I receive is the typical error message one gets when trying to access another runspace directly (without using the dispatcher):

Exception calling "AddChild" with "1" argument(s): "The calling thread cannot access this object because a different thread owns it.

Any ideas what I am doing wrong here? Any kind of help would be much appreciated, thanks!

Try with this :

$syncHash.Window.Dispatcher.Invoke([action]{
    $checkbox = New-Object System.Windows.Controls.CheckBox
    $checkbox.Content = "Hello world"
    $syncHash.CheckboxViewer.AddChild($checkbox)
}, "Normal")

To add a control, you must declare it inside the [action]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM