2014-02-26 82 views
0

我很難讓驗證事件觸發。我創建了一個非常簡單的窗體來展示問題。該表單包含兩個文本框,我希望驗證事件在第一個文本框中按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天,所以任何幫助感激地接受。

回答

0

我沒有看到你連接到Validating事件的地方。將您的$ Code_Validating任務替換爲:

$Code.add_Validating({ 
    $result = ValidateField $sender.Text 
    if ($result) {$eventArgs.Cancel = $true} 
})