BindingSource作为BindingSource与BindingSource作为ViewModel之间的区别

4
我注意到在WinForms中有两种实现数据绑定的方式。然而,我想知道哪一种更受欢迎(例如,在设计时、效率等方面)。据我所知,这两种方式分别为:
- BindingSource 作为 BindingSource:
``` this.textBox1.DataBindings.Add(new Binding("Text", this.myBindingSource, "Augend", true)); ```
- BindingSource 作为 ViewModel:
``` this.textBox1.DataBindings.Add(new Binding("Text", this.myViewModel, "Augend", true)); ```
其中:
- BindingSource 作为 BindingSource 可以在设计时使用窗体的属性窗口轻松实现,并自动生成代码。 - 它通过使用 INotifyPropertyChanged 并简单地调用 OnPropertyChanged 来更新控件,而不需要严格的 PropertyName 值(这对我来说似乎是一个缺点)。 - BindingSource 作为 ViewModel 看起来需要更多的设置工作,没有自动生成和 ViewModel 的 ProeprtyName 匹配。 - 它通过使用 INotifyPropertyChanged 更新控件,但 PropertyName 应该与对象的 Property 相同(这样给人一种保证的感觉)。
我开始更倾向于使用 BindingSource 作为 ViewModel,但如果使用 BindingSource 作为 BindingSource,应用程序的控件设计者会更容易。我相信控件和绑定将松散耦合。他可以随意更改控件,并只使用其属性窗口绑定数据,而不必深入代码并手动更改设置。

BindingSource 是数据绑定的源,也许你的问题是:“使用 BindingSource 还是直接将数据绑定到视图模型更好?” - Reza Aghaei
既然你提到了,我的 this.myBindingSource 技术上是通过属性窗口绑定到 ViewModel 的。我想我的最初想法来自于我展示的代码片段,其中源可以是 ViewModel 或 BindingSource - Lawrence
1个回答

1
然而,我想知道哪一个更受欢迎(例如设计时间、效率等方面的整体表现)?
简言之,没有首选项。
性能上的差异(如果有的话)微不足道。数据绑定涉及很多反射,以计算一些额外的委托调用(在一般情况下,这些都没有人做)。至于设计时支持,它取决于要求,不能用作“整体表现”因素。例如,许多商业应用程序优先使用代码运行时自动生成UI,使用规则和属性(如数据注释),因此根本不需要设计时支持。从另一方面来说,如果您确实需要设计时支持,则没有其他选择,只能使用BindingSource或类似的中介。BindingSource本身不过是一个数据源适配器,在设计时绑定到类型(或小型数据模拟),在运行时绑定到真实实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接