Reputation: 10738
I have two text boxes side by side, InputInches
and InputMillimeters
what I want to do is inches to millimeters conversions similar to the way Goolge conversion works. What I want to happen is that when the user starts typing in the first text box InputInches
the result would be shown in the second text box (InputMillimeters) and vice-versa, if the user starts typing in the second text box the result would be shown in the first text box.
The following code works fine to do inches to millimeters conversion exactly as I want but if I un-comment the code in the convertMillimetersToInches()
method I get an error.
Any suggestion on how can I do this type of binding using MVVM Light?
XAML:
<TextBox x:Name="textBox1"
Text="{Binding InputInches,UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="textBox2"
Text="{Binding InputMillimeters,UpdateSourceTrigger=PropertyChanged}"/>
ViewModel:
namespace MyApp.ViewModel
{
public class ConversionViewModel : ViewModelBase
{
private string _inputInches;
private string _inputInchesTrimmed;
private string _inputMillimeters;
private string _inputMillimetersTrimmed;
public ConversionViewModel()
{
}
public string InputInches
{
get { return _inputInches; }
set {
_inputInches = value;
_inputInchesTrimmed = value.Trim();
RaisePropertyChanged();
if (_inputInchesTrimmed == "") {
_inputInchesTrimmed = "0";
}
convertInchesToMillimeters();
}
}
public string InputMillimeters
{
get { return _inputMillimeters; }
set {
_inputMillimeters = value;
_inputMillimetersTrimmed = value.Trim();
RaisePropertyChanged();
if (_inputMillimetersTrimmed == "") {
_inputMillimetersTrimmed = "0";
}
convertMillimetersToInches();
}
}
/// CONVERSION METHODS
private void convertInchesToMillimeters()
{
double millimeters = Convert.ToDouble(_inputInchesTrimmed) * 25.4;
InputMillimeters = Convert.ToString(millimeters);
}
private void convertMillimetersToInches()
{
//double inches = Convert.ToDouble(_inputInchesTrimmed) / 25.4;
//InputInches = Convert.ToString(inches);
}
}
}
ERROR MESSAGE:
Make sure you don't have an infinite loop or inifinite recursion
Upvotes: 0
Views: 263
Reputation: 1445
Simple answer : Check on your methods the equality before set value (duplicate for other method) :
private void convertInchesToMillimeters()
{
string millimeters = (Convert.ToDouble(_inputInchesTrimmed) * 25.4).ToString();
if(millimeters != InputMillimeters) InputMillimeters = millimeters;
}
More complex answer. Use just one property and implement two wpf converter(see https://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/)
Upvotes: 2