使用 INotifyPropertyChanged (.Net) 进行数据绑定
我正在尝试找到一种在经典 Winforms 中实现 MVP 的好方法,并且我已经找到了一些解决方案(例如 http://codebetter.com/blogs/jeremy.miller/archive/ 2007/05/25/build-you-own-cab-part-3-the-supervising-controller-pattern.aspx)谈论在模型和视图之间使用数据绑定。 我以前从未使用过数据绑定,所以我想尝试一下。
问题是,我无法找到如何使用 INotifyPropertyChanged 进行简单的绑定(例如,模型类中的字符串到表单上的文本框),如上面文章中所建议的。 我以为我已经解决了(这是形式,其中“模型”是我的模型类的实例):
txtModelName.DataBindings.Add(new Binding("Text", model, "Name"));
但是,我很快意识到这根本没有使用 INotifyPropertyChanged - 无论我实现该接口,它都可以正常工作是否在我的模型上。 本身不是问题,但它不能按照我想要的方式工作,主要问题是它是双向绑定(我只想将从对象绑定到< /b> 形式)。
我假设要么有一种不同的使用 INotifyPropertyChanged 的绑定方式,要么如上所述完成的绑定可以设置为仅在一个方向上工作 - 任何人都可以在这里帮忙,或者给我指出一个像样的例子吗?
我使用 .Net 3.5 和经典的 winforms,而不是 WPF。
谢谢
I'm trying to find a good way to implement MVP in classic Winforms, and a couple of solutions I've come accros (e.g. http://codebetter.com/blogs/jeremy.miller/archive/2007/05/25/build-you-own-cab-part-3-the-supervising-controller-pattern.aspx) talk about using data binding between the model and the view. I've never used data binding before, so I thought I'd give it a try.
The trouble is, I can't find out how to do simple binding (e.g. a string in my model class to a textbox on the form) using INotifyPropertyChanged, as suggested in the above article. I thought I had it worked out (this is in the form, where 'model' is an instance of my model class):
txtModelName.DataBindings.Add(new Binding("Text", model, "Name"));
However, I soon realised that this didn't use INotifyPropertyChanged at all - it works fine whether I implement that interface on my model or not. Not a problem in itself, but it doesn't work the way I want it to, the main problem being that it's 2-way binding (I only want to bind from the object to the form).
I'm assuming that either there's a different way of binding using INotifyPropertyChanged, or that binding done as above can be set to only work in one direction - can anyone help out here, or point me towards a decent example?
I'm using .Net 3.5 with classic winforms, not WPF.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,上面的情况有点转移注意力。 发生的事情是我从一个文本框绑定到模型,然后从模型绑定到另一个文本框。 如果我直接更新模型,那么如果不实现 INotifyPropertyChanged,它就无法工作。
至于双向绑定,我认为如果您使用此方法,您就必须忍受它。 如果你不想这样,那就硬着头皮使用 MVP 的“被动视图”风格。
As it turns out, the situation above was a bit of a red herring. What was happening was that I was binding from a textbox to the model, and from the model to another textbox. If I updated the model directly, it wouldn't work without implementing INotifyPropertyChanged.
As for the 2-way binding, I think you just have to live with that if you're using this method. If you don't want that, just bite the bullet and use the 'Passive View' style of MVP.