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

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

我正在尝试使用 PowerShell 中的运行空间来增强小型 GUI 应用程序的性能。

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

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

中声明它