0

我很难让验证事件触发。我创建了一个非常简单的 windows 窗体来演示这个问题。该表单包含两个文本框,我希望在第一个文本框中按下 tab 键时触发验证事件,但事实并非如此。我正在使用在 Windows 7 Professional SP1 下运行的 Powershell V4.0。代码如下: -

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 天,所以任何帮助都感激地接受。

4

1 回答 1

0

我看不到你在哪里连接到Validating活动。将您的 $Code_Validating 分配替换为:

$Code.add_Validating({ 
    $result = ValidateField $sender.Text
    if ($result) {$eventArgs.Cancel = $true}
})
于 2014-02-26T15:03:15.200 回答