Issue
I want to make a m/s to km/h converter that works both ways, just like the one google does. I have used TextChanged in WPF, and it kinda works. My problem is that when I type in for example 7, the program writes 6,9999999..., in the same field. I suspect it is because the 2 fields convert back and forth and finds the most precise number.
I want it to only convert once per field. So if I type 7 in the km/h field it should only convert to m/s and then stop.
Example of me typing in 7, but getting 6,9999999
The 2 methods I use for the program:
private void ms_TextChanged(object sender, TextChangedEventArgs e)
{
if (ms.Text == "")
{
kmh.Text = "";
}
else
{
try
{
kmh.Text = (double.Parse(ms.Text) * 3.6).ToString();
kmh.CaretIndex = kmh.Text.Length;
}
catch (Exception)
{
MessageBox.Show("Input must be a valid number");
}
}
}
private void kmt_TextChanged(object sender, TextChangedEventArgs e)
{
if (kmh.Text == "")
{
ms.Text = "";
}
else
{
try
{
ms.Text = (double.Parse(kmh.Text) / 3.6).ToString();
ms.CaretIndex = ms.Text.Length;
}
catch (Exception)
{
MessageBox.Show("Input must be a valid number");
}
}
}
Solution
Thank you for all the answers. This Link by @Sinatr helped me a lot!
I ended up with this code. I decoupled the Textchanged event before the conversion, did the conversion, and then reattached it.
private void ms_TextChanged(object sender, TextChangedEventArgs e)
{
if (ms.Text == "")
{
kmh.Text = "";
}
else
{
try
{
kmh.TextChanged -= kmh_TextChanged;
kmh.Text = (double.Parse(ms.Text) * 3.6).ToString();
kmh.TextChanged += kmh_TextChanged;
}
catch (Exception)
{
MessageBox.Show("Input must be a valid number");
}
}
}
private void kmt_TextChanged(object sender, TextChangedEventArgs e)
{
if (kmh.Text == "")
{
ms.Text = "";
}
else
{
try
{
ms.TextChanged -= ms_TextChanged;
ms.Text = (double.Parse(kmh.Text) / 3.6).ToString();
ms.TextChanged += ms_TextChanged;
}
catch (Exception)
{
MessageBox.Show("Input must be a valid number");
}
}
}
Answered By - FrederikVil Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.