You are in an infinite loop beacause you change the text in TextChanged
event so it is firing it once again. Rohit Vats answer won't work because TextChanged event is asynchronous - so your case is racy. To better see how it works, I've improved Rohit's answer by adding a SempahoreSlim and waiting for other event to finish. The other problem is that the event is raised only when the value has changed, so we have to check if to wait for the semaphore.
private bool textChanged = false;
SemaphoreSlim sem = new SemaphoreSlim(0, 1);
private async void cambio(object sender, TextChangedEventArgs e)
{
if (!textChanged)
{
TextBox modificado = sender as TextBox;
if (modificado.Name == "t_horizontal")
{
this.ancho = Double.Parse(modificado.Text);
this.diagonal = getDiagonal(this.ancho, this.alto);
}
else if (modificado.Name == "t_vertical")
{
this.alto = Double.Parse(modificado.Text);
this.diagonal = getDiagonal(this.ancho, this.alto);
}
else if (modificado.Name == "t_diagonal")
{
this.diagonal = Double.Parse(modificado.Text);
this.ancho = getAncho(diagonal);
this.alto = getAlto(diagonal);
}
textChanged = true;
if (t_vertical.Text != this.alto + "")
{
t_vertical.Text = this.alto + "";
await sem.WaitAsync(); // wait until finished changing with skip (flag)
}
if (t_horizontal.Text != this.ancho + "")
{
t_horizontal.Text = this.ancho + "";
await sem.WaitAsync(); // wait until finished changing with skip (flag)
}
if (t_diagonal.Text != this.diagonal + "")
{
t_diagonal.Text = this.diagonal + "";
await sem.WaitAsync(); // wait until finished changing with skip (flag)
}
textChanged = false;
}
else sem.Release();
}
Above code is dirty but should show what is happening (don't use it - it is only an example), debug and play with it.
You can also try to make it simpler - by unsubscribing/subscribing to events:
private void cambio(object sender, TextChangedEventArgs e)
{
TextBox modificado = sender as TextBox;
if (modificado.Name == "t_horizontal")
{
this.ancho = Double.Parse(modificado.Text);
this.diagonal = getDiagonal(this.ancho, this.alto);
}
else if (modificado.Name == "t_vertical")
{
this.alto = Double.Parse(modificado.Text);
this.diagonal = getDiagonal(this.ancho, this.alto);
}
else if (modificado.Name == "t_diagonal")
{
this.diagonal = Double.Parse(modificado.Text);
this.ancho = getAncho(diagonal);
this.alto = getAlto(diagonal);
}
t_vertical.TextChanged -= cambio;
t_horizontal.TextChanged -= cambio;
t_diagonal.TextChanged -= cambio;
t_vertical.Text = this.alto + "";
t_horizontal.Text = this.ancho + "";
t_diagonal.Text = this.diagonal + "";
t_vertical.TextChanged += cambio;
t_horizontal.TextChanged += cambio;
t_diagonal.TextChanged += cambio;
}
Of course your code probably should be modified to prevent from such a situation.