ContentControlBase.Validating 事件 (2007 系統)

更新:2007 年 11 月

驗證內容控制項的內容時發生。

命名空間:  Microsoft.Office.Tools.Word
組件:  Microsoft.Office.Tools.Word.v9.0 (在 Microsoft.Office.Tools.Word.v9.0.dll 中)

語法

Public Event Validating As CancelEventHandler

Dim instance As ContentControlBase
Dim handler As CancelEventHandler

AddHandler instance.Validating, handler
public event CancelEventHandler Validating

備註

當控制項遺失焦點時,會引發 Validating 事件。處理 Validating 事件,根據您選擇的準則來判斷內容控制項中的文字是否有效。例如,如果您有包含電話號碼的內容控制項,就可以驗證它是否只包含適當字元 (數字、括號、連字號)。如果內容無效,您可以將事件處理常式之 CancelEventArgs 參數的 Cancel 屬性設定為 true,便會取消事件,並將焦點傳回至控制項。實際效用是使用者無法離開控制項,直到文字有效為止。

若要在成功驗證內容控制項之後執行程式碼,請處理 Validated 事件。

如需處理事件的詳細資訊,請參閱使用事件

範例

下列程式碼範例會示範 Validating 和 Validated 事件的事件處理常式。使用者變更內容控制項中的文字之後,Validating 事件的事件處理常式會使用規則運算式,確認該文字沒有包含整數。

這個範例會假設文件包含名為 plainTextContentControl1 的 PlainTextContentControl。若要使用這段程式碼,請將它貼到專案的 ThisDocument 類別中。若為 C#,您還必須將事件處理常式附加至 plainTextContentControl1 的 Validated 和 Validating 事件。

這是示範文件層級自訂的範例。

Private Sub plainTextContentControl1_Validating(ByVal sender As Object, _
    ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles PlainTextContentControl1.Validating

    Dim control As Microsoft.Office.Tools.Word.PlainTextContentControl = _
        TryCast(sender, Microsoft.Office.Tools.Word.PlainTextContentControl)

    If control IsNot Nothing Then
        Dim regex As New System.Text.RegularExpressions.Regex("\d")
        If regex.IsMatch(control.Text) Then
            MessageBox.Show("Invalid name. Names cannot contain integers.")
            e.Cancel = True
        End If
    End If
End Sub

Private Sub plainTextContentControl1_Validated(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles PlainTextContentControl1.Validated

    MessageBox.Show("The name is valid.")
End Sub
void plainTextContentControl1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    Microsoft.Office.Tools.Word.PlainTextContentControl control =
        sender as Microsoft.Office.Tools.Word.PlainTextContentControl;

    if (control != null)
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d");
        if (regex.IsMatch(control.Text))
        {
            MessageBox.Show("Invalid name. Names cannot contain integers.");
            e.Cancel = true;
        }
    }
}

void plainTextContentControl1_Validated(object sender, EventArgs e)
{
    MessageBox.Show("The name is valid.");
}

使用權限

請參閱

參考

ContentControlBase 類別

ContentControlBase 成員

Microsoft.Office.Tools.Word 命名空間