Forms 对动态生成的控件上的事件使用变量
我有一个函数Forms 对动态生成的控件上的事件使用变量,forms,powershell,Forms,Powershell,我有一个函数addtextbox,它创建一个TextBox控件,并为它的事件处理程序分配一个块 我面临的问题是,该块可能是用全局名称空间调用的,而Add TextBox函数中声明的变量对其不可访问。我如何使它们易于访问 编辑:添加完整代码 Add-Type -AssemblyName System.Windows.Forms Function Add-Control() { Param ( [System.Windows.Forms.Form]$Form,
addtextbox
,它创建一个TextBox
控件,并为它的事件处理程序分配一个块
我面临的问题是,该块可能是用全局名称空间调用的,而Add TextBox
函数中声明的变量对其不可访问。我如何使它们易于访问
编辑:添加完整代码
Add-Type -AssemblyName System.Windows.Forms
Function Add-Control() {
Param (
[System.Windows.Forms.Form]$Form,
[string]$ControlType,
[System.Windows.Forms.Control]$AfterControl = $null,
[int]$Padding = 0
)
$control = New-Object System.Windows.Forms.$ControlType
$control.AutoSize = $true
$x = 5
$y = 5
if ($AfterControl) {
$y = $AfterControl.Location.Y + $AfterControl.Size.Height + $Padding
}
$control.Location = "5,$y"
$form.Controls.Add($control)
return $control
}
Function Add-TextBox() {
Param (
[System.Windows.Forms.Form]$Form,
[string]$Placeholder = "",
[System.Windows.Forms.Control]$AfterControl = $null,
[int]$Padding = 0
)
$control = Add-Control -Form $Form -ControlType "TextBox" -AfterControl $AfterControl -Padding $Padding
$control.Add_GotFocus({
Write-Host "Placeholder is null: $($Placeholder -eq $null)"
if ($this.Text -eq $Placeholder) {
$this.ForeColor = "Black"
$this.Text = ""
}
})
$control.Add_LostFocus({
if ($this.Text -eq "") {
$this.ForeColor = "Darkgray"
$this.Text = $Placeholder
}
})
return $control
}
$form = New-Object system.Windows.Forms.Form
$textbox = Add-TextBox -Form $form -Placeholder "(XXXXXX, npr. 012345)"
$form.ShowDialog()
似乎我可以在脚本块上使用
.GetNewClosure()
来捕获局部变量并保留它们
Add-Type -AssemblyName System.Windows.Forms
Function Add-Control() {
Param (
[System.Windows.Forms.Form]$Form,
[string]$ControlType,
[System.Windows.Forms.Control]$AfterControl = $null,
[int]$Padding = 0
)
$control = New-Object System.Windows.Forms.$ControlType
$control.AutoSize = $true
$x = 5
$y = 5
if ($AfterControl) {
$y = $AfterControl.Location.Y + $AfterControl.Size.Height + $Padding
}
$control.Location = "5,$y"
$form.Controls.Add($control)
return $control
}
Function Add-TextBox() {
Param (
[System.Windows.Forms.Form]$Form,
[string]$Placeholder = "",
[System.Windows.Forms.Control]$AfterControl = $null,
[int]$Padding = 0
)
$control = Add-Control -Form $Form -ControlType "TextBox" -AfterControl $AfterControl -Padding $Padding
$control.Add_GotFocus({
if ($this.Text -eq $Placeholder) {
$this.ForeColor = "Black"
$this.Text = ""
}
}.GetNewClosure()) # Here...
$control.Add_LostFocus({
if ($this.Text -eq "") {
$this.ForeColor = "Darkgray"
$this.Text = $Placeholder
}
}.GetNewClosure()) # And here.
return $control
}
$form = New-Object system.Windows.Forms.Form
$textbox = Add-TextBox -Form $form -Placeholder "(XXXXXX, npr. 012345)"
$form.ShowDialog()