2012-11-14 19 views
1

这是我的Windows应用程序的一个布局,将摄氏转换为华氏。问题是,当我尝试输入温度时会显示一些垃圾(例如:如果我输入'3'则显示'3.0000009'),有时它甚至会显示堆栈溢出异常。输出也没有正确显示:我如何让应用程序正确输入..?

cel.text是摄氏的文本框。 fahre.text是华氏文本框。

namespace PanoramaApp1 
{ 
    public partial class FahretoCel : PhoneApplicationPage 
    { 
    public FahretoCel() 
    { 
     InitializeComponent(); 

    } 

    private void fahre_TextChanged(object sender, TextChangedEventArgs e) 
    { 

     if (fahre.Text != "") 
     { 
      try 
      { 
       double F = Convert.ToDouble(fahre.Text); 
       cel.Text = "" + ((5.0/9.0) * (F - 32)) ; //this is conversion expression 

      } 

      catch (FormatException) 
      { 
       fahre.Text = ""; 
       cel.Text = ""; 
      } 

     } 
     else 
     { 
      cel.Text = ""; 
     } 
    } 

    private void cel_TextChanged(object sender, TextChangedEventArgs e) 
    { 

     if (cel.Text != "") 
     { 
      try 
      { 
       Double c = Convert.ToDouble(cel.Text); 
       fahre.Text = "" + ((c *(9.0/5.0)) + 32); 

      } 
      catch (FormatException) 
      { 
       fahre.Text = ""; 
       cel.Text = ""; 
      } 

     } 
     else 
     { 
      fahre.Text = ""; 
     } 
    } 

} 
} 

回答

1

您可以使用Math.Round将值舍入为小数点后所需的位数。舍入到零将删除小数部分。

变化

cel.Text = "" + ((5.0/9.0) * (F - 32)) ; 

cel.Text = Math.Round(((5.0/9.0) * (F - 32)), 2).ToString() ; 
+0

+0这似乎不是OP的问题 –

+0

它甚至显示堆栈溢出异常部分问题呢? – Zbigniew

2

这是怎么回事,是你的Text_Changed事件处理程序被触发每个-了,他们是不断变化的每一个,其他的文字。

当你从摄氏温度转换成华氏温度时,它会无限转换。

这解释了您的堆栈溢出错误和输入的文本更改。

我会做什么,我会用按钮执行转换还是可以有一个布尔变量打开或关闭其他事件处理程序。

想象这样的事情

protected bool textChangedEnabled = true; 

private void cel_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    if(textChangedEnabled) 
    { 
     textChangedEnabled = false; 
     if (cel.Text != "") 
     { 
      try 
      { 
       Double c = Convert.ToDouble(cel.Text); 
       fahre.Text = "" + ((c *(9.0/5.0)) + 32); 

      } 
      catch (FormatException) 
      { 
       fahre.Text = ""; 
       cel.Text = ""; 
      } 

     } 
     else 
     { 
      fahre.Text = ""; 
     } 
     textChangedEnabled = true; 
    } 
} 

有可能完成它更优雅,更线程安全的方式,但是这只是一个简单的解决。

+0

@des我只是编辑了我的答案。您的事件处理程序会导致每个其他人触发,并且“3.0000009”是其间的舍入错误的结果。 –

+0

是的,现在我明白了,这解释了所有问题。 – Zbigniew

+0

非常感谢...我会尝试..! – user1824343

相关问题