文本框上整数数据类型的 PoCo 验证
我正在开发一个 WPF 应用程序,其中使用绑定到 POCO 实体的 int 字段的文本框,当我清除文本框时,我希望当前对象无效,因为这是一个不可为 null 的字段。
但问题是,当我清除文本框时,它会转换为 string.empty ,无法设置为 int 值,因此我的 int 字段永远不会更新,并且我的对象仍然有效。
请对此提出一些合理的解决方案。
I am developing a WPF application in which i am using a textbox that is bind to an int field of my POCO entity, when i clear the textbox i want my currentobject to be invalid as this is a non nullable field.
But the thing is when i clear my textbox, it convert to string.empty that can ot be set to an int value, so my int field never gets updated and my object remains Valid.
Kindly suggest some logical solution to this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是绑定到字符串值(如果您不想污染模型,可能会添加到视图模型中),然后在字符串属性的 setter 中,将字符串转换为整数以存储在 int 上财产。
One approach is to bind to a string value instead (probably added to a view model if you don't want to pollute your model), and then in the setter for the string property, convert the string to an integer to store on your int property.
正如我所见,您不应该能够为 int 控件设置“空”值。
也许您可以使用 扩展 WPF 工具包 中的 IntegerUpDown 控件,它允许您提供水印,用于显示文本来代替 NULL 值或设置默认值(可以是 0)。
它还有按钮微调器,可以根据需要隐藏。
As i see it, you should not be able to set an 'empty' value to an int control.
Maybe you could use the IntegerUpDown control in the Extended WPF Toolkit which allows you to provide a watermark to show text in place of a NULL Value or set a default value, which could be 0.
It also has button spinners, which can be hidden if needed.
我从此处复制了我的答案。我希望它也对你有帮助。
i copied my answer from here. i hope it helps you too.
默认情况下,当发生验证错误时,WPF 应显示
ErrorTemplate
,这包括由无效转换引起的验证错误,例如尝试将字符串字段存储在int
中。TextBox
的默认ErrorTemplate
是红色边框,对于大多数用户来说,这表明某些内容不正确并且更改将不会保存。如果您想要更多的东西,您可以尝试在绑定中使用
IValueConverter
,它会尝试将值转换为int
,并返回 0 (或一些无效值) )如果失败,那么无论用户输入什么,您的对象都会更新一些内容。By default WPF should display the
ErrorTemplate
when a validation error occurs, and this includes validation errors caused by invalid casts, such as trying to store a string field in anint
. The defaultErrorTemplate
for aTextBox
is a red border, and for most users this is an indication that something is incorrect and the changes will not get saved.If you want something more than that, you could try using an
IValueConverter
in your binding which attempts to cast the value into aint
, and will return 0 (or some invalid value) if it fails so your object will get updated with something no matter what the user enters.