WinForms:如何查找 UserControl 中的所有 BindingSource
在我们正在开发的程序中,用户数据收集在 UserControls 中,这是使用 BindingSources 绑定到业务实体的数据。
我需要以编程方式查找 UserControl 中的所有 BindingSource。
由于 BindingSource 源未添加到 UserControl 的 Controls 集合中,因此我无法在那里搜索。
这可以做到吗?
In the program we are working on, the user data is collected in UserControls which is data bound to a business entity using BindingSources.
I need to find all the BindingSources in a UserControl programatically.
Since a BindingSource source is not added to the UserControl's Controls collection, I cannot search in there.
Can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BindingSource
是一个Component
,而不是Control
,因此您确实无法在Controls
集合中找到它。但是,当您使用设计器添加组件时,它会创建一个名为components
、类型为IContainer
的字段,并向其中添加组件。该字段是私有的,因此您只能从声明它的类中访问它(除非您使用反射)。我认为实现您想要的效果的最简单方法是将
GetBindingSources
方法添加到所有使用的控件中:当然,它仅适用于使用设计器创建的
BindingSources
,不适用于您动态创建的内容(除非您将它们添加到容器中)BindingSource
is aComponent
, not aControl
, so indeed you can't find it in theControls
collection. However, when you add components with the designer, it creates a field namedcomponents
of typeIContainer
and adds the components to it. The field is private, so you can only access it from the class in which it is declared (unless you use reflection).I think the easiest way to achieve what you want is to add a
GetBindingSources
method to all your using controls :Of course, it will work only for
BindingSources
created with the designer, not for those you create dynamically (unless you add them to the container)最大的问题是找到一种解决方案,使我的方法可用于所有 UserControls,并且仍然能够使用 Visual Studio 中的 WinForms 设计器。
因为我不知道在不是从 UserControl 派生的类上使用设计器的任何方法,所以我创建了一个没有任何方法的接口,IBusinessEntityEditorView,以及采用此类视图的扩展方法,使用反射来查找组件字段我在其中搜索我的 BindingSources:
The biggest problem was to find a solution for my method to be available for all the UserControls and still be able to use the WinForms designer from Visual Studio.
Because I don't know any way of using the designer on a class that does not derive from UserControl, I have made an interface without any methods, IBusinessEntityEditorView, and an extension method that takes such a view, uses reflection to find the components field in which I search for my BindingSources: