带有MVVM模式的数字文本框 [英] Numeric text box with MVVM Pattern

查看:86
本文介绍了带有MVVM模式的数字文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了数字TextBox的实现,其代码位于WPF中.我们如何以MVVM模式执行此操作?

I have seen implementations of numeric TextBox with code behind in WPF. How do we do this in MVVM pattern?

推荐答案

老实-MVVM和数字文本框有何共同点?

honestly - what does MVVM and numeric textbox have in common?

如果要使用数字文本框,请创建一个新的TextBox或AttachedProperty或一个行为. 此处是MaskedTextbox行为的示例我的意思.

if you want a numeric textbox you create a new TextBox or AttachedProperty or a Behaviour. Here is an example for a MaskedTextbox behaviour to see what i mean.

现在进入您的MVVM部分.我假设您想验证您的输入只是数字.如果您的视图模型具有一个类型为int的Property,则您的绑定仅在视图获得可转换为int的输入时才有效.否则,您的视图模型将永远不会被通知.现在有2种方法:

now to your MVVM part. i assume that you want to validate your input to be just numeric. if your viewmodel has an Property of type int, then your binding just works if your view got input which is convertable to int. otherwise your viewmodel will never be informed. there are 2 ways now:

首先:确保您的视图仅可以接受数字输入(带有数字文本框),并且viewmodel属性可以为int.

first: you make sure that your view just can take numeric input (with your numeric textbox) and the viewmodel property can be int.

或第二个:您的viewmodel属性类型是typeof字符串,当输入不是数字时,您可以使用IDataErrorInfo通知视图.

or second: your viewmodel property type is typeof string and you use IDataErrorInfo to let the view know when the input is not numeric.

这篇关于带有MVVM模式的数字文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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