简体   繁体   English

未为PictureBox的子控件触发验证事件

[英]Validating event not fired for child controls of picturebox

Yesterday I have implemented some validating events for controls in a groupbox located on a WinForm. 昨天,我已经在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. 我已将窗体的AutoValidate属性设置为Disabled,已将控件的CausesValidation属性设置为true并实现了控件的Validating事件。 By calling the ValidateChildren() method of the form I force that validating events are executed. 通过调用以下形式的ValidateChildren()方法,我强制执行了验证事件。 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;
    }
}

The ValidateChildren() method calls ValidateChildren(ValidationConstraints.Selectable) to get the job done. ValidateChildren()方法调用ValidateChildren(ValidationConstraints.Selectable)来完成工作。 That's a problem for a PictureBox, it isn't selectable. 对于PictureBox来说,这是一个问题,它是无法选择的。 So none of its children get validated either. 因此,它的所有子级都没有得到验证。

Calling it with ValidationConstraints.None doesn't work either, the ability to validate child controls is implemented by ContainerControl and PictureBox doesn't derive from it. 使用ValidationConstraints调用它也无效,ContainerControl实现了验证子控件的能力,PictureBox也不能从中派生。 So you can't call ValidateChildren on the PictureBox either. 因此,您也无法在PictureBox上调用ValidateChildren。 Enumerating the controls yourself and triggering the Validating event can't work either, the PerformControlValidation() method is internal. 自己枚举控件并触发Validating事件也不起作用,PerformControlValidation()方法是内部的。

You'll need to re-think the idea of trying to turn the PictureBox into a ContainerControl. 您需要重新考虑尝试将PictureBox转换为ContainerControl的想法。 Most any control can resemble a picturebox, if not through the BackgroundImage property then through the Paint event. 如果不通过BackgroundImage属性,然后通过Paint事件,则大多数任何控件都可以类似于图片框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM