数据绑定一个WinForms控制,可空类型的最好方法? [英] Best way to databind a Winforms control to a nullable type?

查看:185
本文介绍了数据绑定一个WinForms控制,可空类型的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用的WinForms数据绑定来连接一个数据编辑表单。我使用的是netTiers框架,通过codeSmith生成我的数据对象。对于数据库字段,允许空值它创建可空类型。我发现,使用的WinForms数据绑定控件将不能正确地绑定到可空类型。

I'm currently using winforms databinding to wire up a data editing form. I'm using the netTiers framework through CodeSmith to generate my data objects. For database fields that allow nulls it creates nullable types. I've found that using winforms databinding the controls won't bind properly to nullable types.

我见过的解决方案在线暗示人们创造新的文本框类,可以处理可空类型,但是这可能是不必换出文本框上我已创建的形式痛。

I've seen solutions online suggesting that people create new textbox classes that can handle the nullable types but that could be a pain having to swap out the textboxes on the forms I've already created.

起初,我认为这将是伟大的使用扩展方法来做到这一点。基本上,创造TextBox类并绑定到一个扩展属性。从我有限的扩展方法的经验,并做了一些网上检查它看起来像你不能做一个扩展属性。据我所知,绑定必须通过属性,因为它需要能够获取或设置值,这样的扩展方法是行不通的。

Initially I thought it would be great to use an extension method to do it. Basically creating an extension property for the textbox class and bind to that. From my limited extension method experience and doing a bit of checking online it looks like you can't do an extension property. As far as I can tell, binding has to be through a property since it needs to be able to get or set the value so an extension method wouldn't work.

我很想找到一个干净的方式来改造这些形式使用类似的扩展方法,但如果我要创建新的文本框和组合框控件这就是我要做的。

I'd love to find a clean way to retrofit these forms using something like extension methods but if I have to create new textbox and combo box controls that's what I'll do.

我的项目是目前仅限于NET 2.0,由于要求在Windows 2000上运行。

My project is currently limited to .Net 2.0 due to the requirement to run on Windows 2000.

有什么建议?

推荐答案

在上面的海报中引用文章的评论部分来了一个简单的解决方案。

In the comments section of the article referenced above one of the posters comes up with a simple solution.

textBox1.DataBindings.Add("Text", myClass, "MyTextProperty");

与绑定:

textBox1.DataBindings.Add("Text", myClass, "MyTextProperty", true, DataSourceUpdateMode.OnPropertyChanged, string.Empty); 

这篇关于数据绑定一个WinForms控制,可空类型的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆