我注意到在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:
``` 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 Aghaeithis.myBindingSource
技术上是通过属性窗口绑定到 ViewModel 的。我想我的最初想法来自于我展示的代码片段,其中源可以是 ViewModel 或BindingSource
。 - Lawrence