从 UserControl 传回信息

phr*_*tic 1 c# validation winforms

我刚刚开始掌握 UserControl 的概念。

我创建了一个 UserControl 来将多个在 TabControl 的各个页面上复制的控件组合在一起。

其中一些控件是需要验证的文本字段,当验证不成功时,我需要显示错误消息。但是,我想显示错误消息的位置在主窗体的状态栏上。

在这种情况下处理验证/错误显示的最佳方法是什么?

Dan*_*ant 5

要处理验证,请执行以下操作之一:

  • 使用用户控件内的方法进行验证
  • 让您的用户控件具有一个可以处理验证的delegate属性(例如ValidationHandler)(这将允许您拥有一个带有一堆验证器的类,您可以将这些验证器分配给您的控件)

    public delegate void Validator(...)

    public Validator ValidationHandler { get; set; }

  • 让您的用户控件生成验证请求event(例如ValidationRequested

    public event EventHandler<ValidationEventArgs> ValidationRequested

要通知系统发生了错误,请执行以下操作之一:

  • 使用event感兴趣的各方可以订阅的(例如ValidationFailed

  • 如果执行验证(通过delegateevent)的对象也是您想要从中生成错误消息的对象,则它可以自己引发错误消息。

编辑:

由于您已经说过要在控件内部进行验证,因此 ValidationFailed 事件的代码可能如下所示:

// In your user control

public class ValidationFailedEventArgs : EventArgs
{
   public ValidationFailedEventArgs(string message)
   {
      this.Message = message;
   }

   public string Message { get; set; }
}

private EventHandler<ValidationFailedEventArgs> _validationFailed;
public event EventHandler<ValidationFailedEventArgs> ValidationFailed
{
   add { _validationFailed += value; }
   remove { _validationFailed -= value; }
}

protected void OnValidationFailed(ValidationFailedEventArgs e)
{
   if(_validationFailed != null)
      _validationFailed(this, e);
}

private void YourValidator()
{
   if(!valid)
   {
      ValidationFailedEventArgs args = 
         new ValidationFailedEventArgs("Your Message");
      OnValidationFailed(args);
   }
}

// In your main form:

userControl.ValidationFailed += 
   new EventHandler<ValidationFailedEventArgs>(userControl_ValidationFailed);

// ...
private void userControl_ValidationFailed(object sender, 
                                          ValidationFailedEventArgs e)
{
   statusBar.Text = e.Message;
}
Run Code Online (Sandbox Code Playgroud)