如何在Powershell中调用另一个运行空间中运行的WPF表单元素的方法

我正在使用Power
Shell中的运行空间来增强小型GUI应用程序的性能.

到目前为止我所拥有的是一个有两个目的的运行空间:首先,它包含我所有的其他运行空间,其次,它解析我的GUI xml文件并显示它.
它还将节点添加到同步哈希表中,因此我可以在所有运行空间中访问它.你可以想象我在这个GUI中有一些按钮,它们在点击时触发动作;非常简单的东西,实际上它到目前为止工作得很好.我可以在运行空间之间交换数据,我也可以在单击某个按钮时更新GUI.

但是,我无法在xml文件中的空stackpanel上调用addChild()方法.我基本上想要做的只是将复选框添加到stackpanel(名为“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")

我收到的错误消息是尝试直接访问另一个运行空间时获得的典型错误消息(不使用调度程序):

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

我在这里做错了什么想法?任何形式的帮助将非常感谢,谢谢!

最佳答案 试试这个:

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

要添加控件,必须在[action]中声明它

点赞