用户控制数据绑定的最佳实践 - 如何实现这一点?

发布于 2024-09-11 16:48:42 字数 142 浏览 3 评论 0原文

我有一个带有文本框、标签等的用户控件。现在我想获得相同的数据绑定功能,就像我将控件直接放置在表单上一样。我尝试在用户控件中使用额外的绑定源和错误提供程序,并尝试将控件的属性作为属性提供。

什么都没起作用。所以必须有一个解决方案来完成这个任务。那么如何呢?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我也只是我 2024-09-18 16:48:42

我在 https://github.com/edymtt/usercontrolwithdatabinding 实现了一个示例来说明一些数据绑定可能适用于您的问题的场景。我特别讨论了两种场景:

  1. 实现 UserControl 来编辑基本属性(字符串、整数等);
  2. 实现UserControl来编辑复杂类型的属性(例如Address POCO);

实现用于编辑基本属性的 UserControl

在这种情况下,公开底层控件的相关属性就足够了(例如 TextBox< 的 Text 属性) /code>)并在发生变化时引发适当的事件(继续该示例,处理 TextBoxTextChanged 事件并引发新的 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:

  1. Realization of an UserControl to edit a basic property (string, integer, ...);
  2. Realization of an UserControl to edit a property of a complex type (such as an Address POCO);

Realization of an UserControl to edit a basic property

In this case it suffices to expose the relevant property of an underlying control (for example the Text property of a TextBox) and to raise an appropriate event when this changes (continuing the example, handle the TextChanged event of the TextBox and raise a new TextChanged 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 problem

Realization of an UserControl to edit a property of a complex type

This case is not much complex than the previous:

  • you need to put a BindingSource and an Error Provider in the usercontrol to handle the POCO you need;
  • next you need expose a property to receive the bound object and assign it at runtime.

I hope that the sample is clear enough to understand how the binding works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文