Zależne NumericUpDown

0

Cześć,
w aplikacji chcę umieścić zależne od siebie kontrolki NumericUpDow. Wartość jednej ma ma się zmieniać proporcjonalnie do zmiany wartości drugiej. Ze wzoru x/y = x'/y', gdzie x, y są początkowymi wartościami, a x', y' tymi nowymi, wyprowadziłem sobie x' oraz y' i przystąpiłem do realizacji tego zadania. Oto efekt:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Test
{
	public partial class Form1 : Form
	{
		EventHandler a, b;

		public Form1()
		{
			InitializeComponent();

			numericUpDown1.Maximum = decimal.MaxValue;
			numericUpDown2.Maximum = decimal.MaxValue;

			numericUpDown1.Minimum = 1;
			numericUpDown2.Minimum = 1;

			// przykładowe wartości 
			decimal val1 = 640;
			decimal val2 = 400;

			numericUpDown1.Value = val1;
			numericUpDown2.Value = val2;

			a = (object sender, EventArgs e) =>
			{
				numericUpDown2.ValueChanged -= b;

				decimal y = val2;
				decimal x = val1;
				decimal _x = (sender as NumericUpDown).Value;
				decimal _y = (y * _x) / x;

				numericUpDown2.Value = _y;

				numericUpDown2.ValueChanged += b;
			};

			b = (object sender, EventArgs e) =>
			{
				numericUpDown1.ValueChanged -= a;

				decimal y = val2;
				decimal x = val1;
				decimal _y = (sender as NumericUpDown).Value;
				decimal _x = (x * _y) / y;

				numericUpDown1.Value = _x;

				numericUpDown1.ValueChanged += a;
			};

			numericUpDown1.ValueChanged += a;
			numericUpDown2.ValueChanged += b;
		}
	}
}

I teraz rodzi się pytanie. Czy da się to zrobić bardziej elegancko? Nie podobają mi się te manewry ze zdarzeniami przy zmianie wartości, a nie mam innego pomysłu.

0

ja bym dodał wartość boolean do kontrolowania zdarzeń:

			bool changing = false;

			numericUpDown1.ValueChanged += (s, e) =>
			{
				if (changing) return;
				changing = true;

				decimal _x = numericUpDown1.Value;
				decimal _y = (val2 * _x) / val1;

				numericUpDown2.Value = _y;
				changing = false;
			};

			numericUpDown2.ValueChanged += (s, e) =>
			{
				if (changing) return;
				changing = true;

				decimal _y = numericUpDown2.Value;
				decimal _x = (val1 * _y) / val2;

				numericUpDown1.Value = _x;
				changing = false;
			};
0

albo krócej:

bool changing = false;
 
 Func<int, int, NumericUpDown, EventHandler> ev = (v1, v2, n) => (s, e) => {
   if(changing ^= true) return;
   decimal a = (s as NumericUpDown).Value;
   n.value = (v1 * a) / v2;
   changing = false;
 };
 
 numericUpDown1.ValueChanged += ev(val2, val1, numericUpDown2);
 numericUpDown2.ValueChanged += ev(val1, val2, numericUpDown1);

(niesprawdzone)

1 użytkowników online, w tym zalogowanych: 0, gości: 1