问题描述
我使用的是 C#.
为什么 CausesValidation 属性不会从容器传播到子控件?
Why does the CausesValidation property does not propagate from containers to child controls?
我有一个 TabControl,我需要对所有选项卡上的用户输入进行验证.但是每个选项卡都是独立的.我发现如果我有一个像 TableLayoutPanel 这样的容器并且我将 CausesValidation 设置为 false,子组件仍然执行验证.
I have a TabControl and i need to perform validation of user input on all tabs.But each tab is independent. I found out that if i have a container like a TableLayoutPanel and i set CausesValidation to false, the child componentes still perform validation.
所以这段代码不起作用:
So this code would not work:
Foreach(Control c in Container.Controls)
{
c.CausesValidation = False;
}
如果您执行一些调试输出,您将看到唯一找到的控件是 TableLayoutPanel 或任何其他容器,如将被找到并设置为 False 的 GroupBox.但是容器不会将该值传播到子级别.很多人问我们如何解决这个问题.我找到了很多方法,但我创建了一个静态类,允许我在 TabControl 上选择要执行验证的选项卡,并且它将在该 TabControl 的所有控件上设置 CausesValidation 为 False,包括带有10层的深度.如果你想要那个图书馆,就要求吧!
If you do some DEBUG output you will see that the only found control is the TableLayoutPanel or any other container like a GroupBox that will be found and set to False. But containers are not propagating that value to the child level.A lot of people asked how we could solve the problem. I found a lot of methods, but i have created a static class that allows me to select wich tab on the TabControl that i want to perform validation, and it will set CausesValidation to False on ALL controls of that TabControl, including child controls with a deepness of 10 layers. If you want that library just ask for it!
我真正的问题是,容器不应该将该属性传播给它的子控件,而该子控件应该传播给任何子控件吗?!
My real question is, should not a container propagate that property to its child controls, and that child controls to any child controls?!
它可以为我们节省大量工作,无需创建非常疯狂的代码,该代码非常特定于应该从头开始工作的东西?为什么这不是暗示?
It would save us a lot of work from creating a very crazy code that is very specific for something that should work from scratch? Why is this not implied?
推荐答案
这不是处理您的需求的建设性方式.该功能并未按照您喜欢的方式实现,而且永远不会改变.这不是问题,您可以使用一点代码轻松添加它:
This just isn't a constructive way to deal with your requirement. The feature just wasn't implemented the way you like it to work and that's never going to change. It isn't a problem, you can easily add it yourself with a wee bit of code:
public static void SetCausesValidation(Control.ControlCollection ctls, bool enable) {
foreach (Control ctl in ctls) {
ctl.CausesValidation = enable;
SetCausesValidation(ctl.Controls, enable);
}
}
并在您的表单构造函数中使用它,例如:
And use it in your form constructor, something like:
public Form1() {
InitializeComponent();
SetCausesValidation(panel1.Controls, false);
}
注意方法中递归的使用,通过容器内的整个控件树来设置属性.
Note the use of recursion in the method to set the property through the entire tree of controls inside the container.
这篇关于为什么 CausesValidation 不会从容器传播到子控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!