0

Yesterday I have implemented some validating events for controls in a groupbox located on a WinForm. I have set the AutoValidate property of the form to Disabled, I have set the CausesValidation property of the controls to true and implemented the Validating event of the controls. By calling the ValidateChildren() method of the form I force that validating events are executed. This was working all fine.

But after placing this groupbox on top of a picturebox and setting the picturebox as parent of the groupbox then validating events aren't executed anymore....

Below some demo code. Form is only containing a picturebox, groupbox, textbox and button.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        MessageBox.Show("Validating textbox");
        e.Cancel = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (ValidateChildren())
            MessageBox.Show("Validation not executed :-(");
        else
            MessageBox.Show("Validation executed :-)");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        groupBox1.Parent = pictureBox1;
    }
}
4

1 回答 1

1

ValidateChildren() 方法调用 ValidateChildren(ValidationConstraints.Selectable) 来完成工作。这是一个 PictureBox 的问题,它是不可选择的。所以它的孩子也没有得到验证。

用 ValidationConstraints.None 调用它也不起作用,验证子控件的能力是由 ContainerControl 实现的,而 PictureBox 不是从它派生的。所以你也不能在 PictureBox 上调用 ValidateChildren。自己枚举控件并触发 Validating 事件也不起作用,PerformControlValidation() 方法是内部的。

您需要重新考虑尝试将 PictureBox 变成 ContainerControl 的想法。大多数控件都可以类似于图片框,如果不是通过 BackgroundImage 属性然后通过 Paint 事件。

于 2012-08-01T10:13:19.293 回答