使用 INotifyPropertyChanged (.Net) 进行数据绑定

发布于 2024-08-02 02:28:17 字数 936 浏览 4 评论 0原文

我正在尝试找到一种在经典 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 技术交流群。

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

发布评论

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

评论(1

裂开嘴轻声笑有多痛 2024-08-09 02:28:17

事实证明,上面的情况有点转移注意力。 发生的事情是我从一个文本框绑定到模型,然后从模型绑定到另一个文本框。 如果我直接更新模型,那么如果不实现 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.

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