WP7:将一组文本框从文本转换为数字或十进制值的最简单方法是什么?
因此,我让用户在多个文本框中输入数字,我需要检查它们是否不为空并将它们转换为十进制。有没有比为每个文本框使用单独的 IF 更简单的方法?
if (txtBoxAuto1.Text != null)
{
String varStrTxtBox1 = txtBoxAuto1.Text;
decimal varTxtBox1 = Decimal.Parse(varStrTxtBox1);
}
我尝试在第一个文本框后面添加一个“和”,但它似乎不喜欢它。
So I have users inputting numbers into multiple text boxes and I need to check that they are not null and convert them to decimal. Is there a simpler way to do this than a separate IF for each textbox?
if (txtBoxAuto1.Text != null)
{
String varStrTxtBox1 = txtBoxAuto1.Text;
decimal varTxtBox1 = Decimal.Parse(varStrTxtBox1);
}
I tried putting an "and" after the first textbox and it didn't seem to like it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我做这样的事情时,我将文本框添加到列表中以循环思考它们。
或者,如果您在面板中拥有所有文本框,您可以循环认为它们就像
或者我错过了重点吗?
When I did such stuff, I added the Textboxes into a list to loop thought them.
Or if you have all Textboxes in a panel you can loop thought them just like
Or did I miss the point?
C# 中的逻辑与是 &&。
如果所有文本框都必须为 NOT NULL,则只需在 if 语句条件中添加逻辑 AND。否则,如果某些可以为 NULL 而其他则不能,则您需要为每个可以为 NULL 的文本框使用单独的 IF 语句。
The logical AND in C# is &&.
If all of the text boxes have to NOT be NULL, then just add the logical AND in the if statement condition. Otherwise, if some can be NULL and not others, you'll need a separate IF statement for each of the text boxes which can be NULL.
假设您在 WP7 上使用 WPF/Silverlight:最好遵循模型-视图-视图模型 ( MVVM) 模式与其他 WPF/Silverlight 应用程序一样并使用数据绑定。
我会使用一个公开的视图模型来处理它:
FirstNumberText
的“外部”(视图)数据绑定字符串属性或您想要的任何内容 - 这是绑定到文本框的属性。FirstNumber
,它动态解析FirstNumberText
并包含所需的任何其他业务逻辑 - 您将在以下情况下调用它您需要实际的Decimal
数字。这也意味着无效条目不会导致数据绑定失败,因此您可以轻松使用数据绑定的内置验证功能(包括方便的 属性),如果输入的文本为空或以其他方式不合适(负面、太大/太小、 ETC)。
由于您使用的是 MVVM,而不是直接从视图中与控件交互,因此您还可以从根本上更改界面,而不必担心破坏逻辑(通过删除/重命名控件)。
Assuming that you're using WPF/Silverlight on WP7: it is probably best to follow the model-view-viewmodel (MVVM) pattern as with other WPF/Silverlight apps and use databinding.
I'd approach it with a viewmodel that exposes:
FirstNumberText
or whatever you want - this is the one that is bound to the textbox.FirstNumber
that parsesFirstNumberText
on the fly and contains whatever other business logic is required - you'll call this when you want the actualDecimal
number.This also means that invalid entries won't cause databinding to fail, so you can trivially use the built in validation functionality of databinding (including handy attributes) to deliver a friendly error message to the user if the text entered is empty or is inappropriate in some other way (negative, too big/small, etc).
Since you're using MVVM instead of directly interacting with controls from the view, you can also radically change the interface without worrying as much about breaking logic (by removing/renaming controls).