在验证内容控件的内容时发生。
命名空间: Microsoft.Office.Tools.Word
程序集: Microsoft.Office.Tools.Word(在 Microsoft.Office.Tools.Word.dll 中)
语法
声明
Event Validating As CancelEventHandler
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.");
}
.NET Framework 安全性
- 对直接调用方的完全信任。此成员不能由部分信任的代码使用。有关更多信息,请参见通过部分受信任的代码使用库。