用户控制数据绑定的最佳实践 - 如何实现这一点?
我有一个带有文本框、标签等的用户控件。现在我想获得相同的数据绑定功能,就像我将控件直接放置在表单上一样。我尝试在用户控件中使用额外的绑定源和错误提供程序,并尝试将控件的属性作为属性提供。
什么都没起作用。所以必须有一个解决方案来完成这个任务。那么如何呢?
I've got an User Control with TextBoxes, Labels, ... . Now I would like to get the same Data Binding Features like I would place the Controls directly on the Form. I tried with an extra Binding Source and Error Provider in the User Control and I tried to make the Properties of my Controls available as an property.
Nothing worked. So there have to be an solution to get this done. So how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 https://github.com/edymtt/usercontrolwithdatabinding 实现了一个示例来说明一些数据绑定可能适用于您的问题的场景。我特别讨论了两种场景:
UserControl
来编辑复杂类型的属性(例如Address
POCO);实现用于编辑基本属性的
UserControl
在这种情况下,公开底层控件的相关属性就足够了(例如
TextBox< 的
Text
属性) /code>)并在发生变化时引发适当的事件(继续该示例,处理TextBox
的TextChanged
事件并引发新的TextChanged
> 事件,请参阅 MSDN 上的此页面的“更改通知”部分表单中的
ErrorProvider
(您拥有绑定源)可以毫无问题地处理此类 UserControl实现用于编辑复杂属性的
UserControl 这种情况
并不比前一种复杂:
BindingSource
和一个Error Provider
来处理您需要的 POCO,我希望该示例足够清晰,能够理解绑定的工作原理。
I've realized a sample at https://github.com/edymtt/usercontrolwithdatabinding to illustrate some data binding scenarios that may apply to your question. In particular I've addressed two scenarios:
UserControl
to edit a basic property (string, integer, ...);UserControl
to edit a property of a complex type (such as anAddress
POCO);Realization of an
UserControl
to edit a basic propertyIn this case it suffices to expose the relevant property of an underlying control (for example the
Text
property of aTextBox
) and to raise an appropriate event when this changes (continuing the example, handle theTextChanged
event of theTextBox
and raise a newTextChanged
event, see this page on MSDN at the section "Change Notification for Custom Controls).The
ErrorProvider
in the form (where you have the binding source) can handle this kind of UserControl without problemRealization of an
UserControl
to edit a property of a complex typeThis case is not much complex than the previous:
BindingSource
and anError Provider
in the usercontrol to handle the POCO you need;I hope that the sample is clear enough to understand how the binding works.