如何在Visual Studio 2019中实现多个文本框数值求和并自动展示?
Visual Studio 2019 多文本框自动求和实现方案
以下覆盖WinForm、WPF两种常用桌面项目场景:
WinForm 实现步骤
- 步骤1:统一绑定文本变更事件
在窗体设计器中同时选中6个输入用文本框,右键打开「属性」面板,点击闪电形状的「事件」图标,找到TextChanged事件,输入自定义事件名(如InputBox_TextChanged)后回车,自动生成事件方法框架。 - 步骤2:编写求和逻辑
在生成的事件方法中添加如下代码,注意替换代码中的文本框名称为你实际定义的名称:
private void InputBox_TextChanged(object sender, EventArgs e) { decimal sum = 0; // 替换为你自己的6个输入文本框控件名 TextBox[] inputBoxes = { txtInput1, txtInput2, txtInput3, txtInput4, txtInput5, txtInput6 }; foreach (var box in inputBoxes) { // 非数字输入默认按0计算,避免报错 if (decimal.TryParse(box.Text, out decimal currentNum)) { sum += currentNum; } } // 替换为你自己的总和展示文本框控件名 txtTotal.Text = sum.ToString(); }
- 可选优化:限制仅允许输入数字
可以给6个输入文本框统一绑定KeyPress事件,过滤非法输入:
private void InputBox_KeyPress(object sender, KeyPressEventArgs e) { // 允许数字、退格键、小数点输入 if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.') { e.Handled = true; } // 限制仅能输入一个小数点 if (e.KeyChar == '.' && (sender as TextBox).Text.Contains(".")) { e.Handled = true; } }
WPF 实现步骤(MVVM 规范写法)
无需额外编写事件代码,通过绑定机制自动触发计算:
- 步骤1:创建ViewModel类,代码示例如下:
using System.ComponentModel; using System.Runtime.CompilerServices; public class SumViewModel : INotifyPropertyChanged { // 第1个输入值属性,Input2~Input6写法完全一致,此处省略重复代码 private decimal _input1; public decimal Input1 { get => _input1; set { _input1 = value; OnPropertyChanged(); // 输入值变更时通知总和属性更新 OnPropertyChanged(nameof(Total)); } } // 总和只读属性,自动计算6个输入值的和 public decimal Total => Input1 + Input2 + Input3 + Input4 + Input5 + Input6; public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
- 步骤2:XAML 绑定控件
给页面绑定上述ViewModel后,编写控件绑定代码:
<!-- 输入文本框示例,其余5个分别绑定Input2~Input6即可 --> <TextBox Text="{Binding Input1, UpdateSourceTrigger=PropertyChanged}"/> <!-- 总和展示文本框,设置为只读 --> <TextBox Text="{Binding Total}" IsReadOnly="True"/>
内容的提问来源于stack exchange,提问作者lme1999007
相关产品推荐
相关产品推荐

