WPF C#货币转换器ComboBox选中项无法计算输出问题求助
问题分析与修复
你的货币转换器无输出也不报错的核心原因是:ComboBox的SelectedItem返回的是ComboBoxItem实例对象,不是字符串,你直接用CboFrom.SelectedItem == "USD"这种字符串比较逻辑永远不成立,导致两个条件分支都不会执行,所以TextBoxTotal不会被赋值。
修复方案
方案1:直接获取ComboBoxItem的Content属性做判断
修改后台点击事件代码,先将SelectedItem转换为ComboBoxItem,再取Content值进行比较:
private void ButtonConvert_Click(object sender, RoutedEventArgs e) { // 输入验证:避免非数字输入触发异常 if (!double.TryParse(TextBoxAmount.Text, out double amount)) { TextBoxTotal.Text = "请输入有效数字"; return; } double tot; // 获取下拉框选中项的文本内容 string fromCurrency = ((ComboBoxItem)CboFrom.SelectedItem).Content.ToString(); string toCurrency = ((ComboBoxItem)CboTo.SelectedItem).Content.ToString(); if (fromCurrency == "USD" && toCurrency == "Srilankan Rupees") { tot = amount * 179.50; TextBoxTotal.Text = tot.ToString("N2"); // 格式化保留两位小数,符合货币显示习惯 } else if (fromCurrency == "USD" && toCurrency == "Indian Rupees") { tot = amount * 70; TextBoxTotal.Text = tot.ToString("N2"); } else { TextBoxTotal.Text = "不支持的转换类型"; } }
方案2:更规范的ComboBox绑定方式(推荐)
修改XAML中的ComboBox配置,通过SelectedValuePath和DisplayMemberPath让SelectedValue直接返回字符串,简化判断逻辑:
修改后的XAML(ComboBox部分)
<ComboBox Name="CboFrom" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="25" Grid.Row="2" Grid.Column="1" SelectedValuePath="Tag" DisplayMemberPath="Content"> <ComboBoxItem Content="USD" Tag="USD"/> </ComboBox> <ComboBox Name="CboTo" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="25" Grid.Row="4" Grid.Column="1" SelectedValuePath="Tag" DisplayMemberPath="Content"> <ComboBoxItem Content="Srilankan Rupees" Tag="LKR"/> <ComboBoxItem Content="Indian Rupees" Tag="INR"/> </ComboBox>
对应后台代码
private void ButtonConvert_Click(object sender, RoutedEventArgs e) { if (!double.TryParse(TextBoxAmount.Text, out double amount)) { TextBoxTotal.Text = "请输入有效数字"; return; } double tot; string fromCurrency = CboFrom.SelectedValue.ToString(); string toCurrency = CboTo.SelectedValue.ToString(); if (fromCurrency == "USD" && toCurrency == "LKR") { tot = amount * 179.50; TextBoxTotal.Text = tot.ToString("N2"); } else if (fromCurrency == "USD" && toCurrency == "INR") { tot = amount * 70; TextBoxTotal.Text = tot.ToString("N2"); } else { TextBoxTotal.Text = "不支持的转换类型"; } }
额外优化说明
- 输入验证:用
double.TryParse替代double.Parse,避免非法输入导致程序崩溃 - 输出格式化:通过
ToString("N2")保留两位小数,让结果更符合货币展示需求 - 异常分支:增加else分支处理未匹配的转换场景,给用户明确反馈
内容的提问来源于stack exchange,提问作者abi jega
相关产品推荐
相关产品推荐

