我有一个 winform 应用程序,点击后会填充一些数据$button_UpdateTS
,如何添加存储在变量中的数据,单击该按钮后可用?
我想要在列表视图中显示的数据存储在一个名为的数组中$results
$button_UpdateTS = New-Object System.Windows.Forms.Button
$button_UpdateTS.Location = New-Object System.Drawing.Size(15, 954)
$button_UpdateTS.Size = New-Object System.Drawing.Size(320, 32)
$button_UpdateTS.TextAlign = "MiddleCenter"
$button_UpdateTS.Text = “Update Tasksequence”
$button_UpdateTS.Add_Click( { $Results = Set-DynamicVariables
-Manufacturer "$($listview_Vendor.SelectedItems)"
-TSPackageID "$($ListView_Tasksequences.SelectedItems.SubItems[1].Text)" -WhatIf })
$Form.Controls.Add($button_UpdateTS)
这给了我:
$Results =
SKUNotExistsDriverName : XPS Notebook 9560
SKUNotExistsDriverID : PS10053F
SKUNotExistsDriverSKU : 07BE
SKUNotExistsDriverVersion : A12
SKUNotExistsBIOSName : XPS Notebook 9560
SKUNotExistsBIOSID : PS10053E
SKUNotExistsBIOSSKU : 07BE
SKUNotExistsBIOSVersion : 1.15.0
这是我希望将其存储在的列表:
$Global:listview_NotExists_SKU = New-Object System.Windows.Forms.ListView
$listview_NotExists_SKU.Location = New-Object System.Drawing.Size(515, 670)
$listview_NotExists_SKU.Size = New-Object System.Drawing.Size(486, 235)
$listview_NotExists_SKU.View = "Details"
$listview_NotExists_SKU.FullRowSelect = $true
$listview_NotExists_SKU.MultiSelect = $true
$listview_NotExists_SKU.Sorting = "None"
$listview_NotExists_SKU.AllowColumnReorder = $true
$listview_NotExists_SKU.GridLines = $true
$listview_NotExists_SKU.Add_ColumnClick( { SortListView $this $_.Column })
$Form.Controls.Add($listview_NotExists_SKU)
我尝试使用此功能,但不起作用:
Function Get-Results {
ForEach ($Result in $Results) {
$listview_NotExists_SKU.Items.Add($Result)
}
}
$Form.Add_Shown( { $Form.Load; Get-results })
Because 添加了事件处理脚本块,例如.Add_Click()
运行在child调用者的范围,分配给变量$Results
there ($Results = ...
) 创建一个作用域局部多变的设置事件处理程序的范围和随后调用的事件处理程序都看不到。
To create a variable in the script scope, which subsequently invoked event handlers can see as well[1], use the $script:
scope specifier:
$button_UpdateTS.Add_Click( { $script:Results = ... } )
Note:
-
If the scope in which the event handlers are set up isn't the script scope (e.g., if the code is inside a function) and you want to more generically reference that scope from within an event handler, use Set-Variable -Scope 1 -Name Results -Value ...
, which targets the respective parent scope.[1]
-
An alternative to setting a variable in the parent scope explicitly is to use a hashtable defined in the parent scope whose entries can be used in lieu of variables that the event-handler script blocks can modify too.[2] See this answer for an example.
[1] For more information about scopes in PowerShell, see the bottom section of this answer.
[2] This technique works, because even though the variable containing the hashtable is defined in the parent scope, the child scope can access its value and modify the entries of the referenced hashtable object rather than the variable itself.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)