我在触发验证事件时遇到了真正的麻烦。我创建了一个非常简单的窗口窗体来演示该问题。该表单包含两个文本框,我希望在第一个文本框中按下 Tab 键时触发验证事件,但事实并非如此。我使用的是Powershell V4.0,在Windows 7 Professional SP1下运行。代码如下:-
Function ValidateField( [string]$FieldValue )
{
Write-Host "ValidateField: Function Entered"
if ( $FieldValue -eq $Null -Or $FieldValue.Trim().Length -eq 0 ) { Return $True } else { Return $False }
}
Function GenerateForm
{
Write-Host "GenerateForm: Function Entered"
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null
[Reflection.Assembly]::LoadWithPartialName( "System.Drawing" ) | Out-Null
$Form = New-Object System.Windows.Forms.Form ; $IFWS = New-Object System.Windows.Forms.FormWindowState
$Code = New-Object System.Windows.Forms.TextBox ; $Desc = New-Object System.Windows.Forms.TextBox
$Form.ClientSize = New-Object System.Drawing.Size( 400,200 )
$Form.StartPosition = "CenterScreen" ; $Form.add_Load( $FormLoad )
$OnLoadForm_StateCorrection = { $Form.WindowState = $IFWS }
$Code.DataBindings.DefaultDataSourceUpdateMode = 0 ; $Code.Location = New-Object System.Drawing.Size( 10,10 )
$Code.Size = New-Object System.Drawing.Size( 40,20 ) ; $Code.CausesValidation = $True
$Code_Validating = [System.ComponentModel.CancelEventHandler] {
{ $Result = ( ValidateField $Code.Text )
if ( $Result -eq $True ) { $_.Cancel = $True } }
}
$Form.Controls.Add( $Code )
$Desc.DataBindings.DefaultDataSourceUpdateMode = 0 ; $Desc.Location = New-Object System.Drawing.Size( 100,10 )
$Desc.Size = New-Object System.Drawing.Size( 169,20 ) ; $Form.Controls.Add( $Desc )
$IFWS = $Form.WindowState ; $Form.add_Load( $OnLoadForm_StateCorrection ) ; $Form.ShowDialog() | Out-Null
}
GenerateForm
很可能我只是错过了一些非常简单的东西 - 但这已经让我发疯了 3 天了,所以任何帮助都感激地接受了。
我没有看到您连接到Validating
事件的位置。将 $Code_验证分配替换为:
$Code.add_Validating({
$result = ValidateField $sender.Text
if ($result) {$eventArgs.Cancel = $true}
})