ここに考えがあります-「TextBoxManager」と呼ばれるクラスを作成します:
public class TextBoxManager
{
public List<Tuple<TextBox, TextBox>> LowerHigherPairs { get; set; }
public TextBoxManager()
{
LowerHigherPairs = new List<Tuple<TextBox, TextBox>>();
}
public void RegisterTextBoxes(TextBox lower, TextBox higher)
{
lower.Leave += TextBoxFocusLost;
higher.Leave += TextBoxFocusLost;
LowerHigherPairs.Add(new Tuple<TextBox, TextBox>(lower, higher));
}
public void TextBoxFocusLost(object sender, EventArgs e)
{
TextBox senderBox = sender as TextBox;
Tuple<TextBox, TextBox> matchingPair = LowerHigherPairs.Find(x => x.Item1 == senderBox || x.Item2 == senderBox);
if (matchingPair != null)
{
if (matchingPair.Item1 == senderBox)
{
//We know we should compare with the value in Item2.Text
}
else
{
//We know we should compare with the value in Item1.Text
}
}
}
}
フォームで、これをクラスレベルの変数として宣言します。
TextBoxManager higherLowerManager = new TextBoxManager();
次に、フォームのOnLoadイベントで、管理するテキストボックスのペアを登録するだけです。
higherLowerManager.RegisterTextBoxes(lowerEntryTextBox, higherEntryTextBox);
ご覧のとおり、このクラスは2つをペアにして、どちらが適切かを判断し、適切なロジックを実行できる共通のイベントにサブスクライブします。
これを行うもう1つの方法は、UserControlを使用することです。これにより、動的レイアウトの柔軟性が失われますが、インタラクション全体が適切にカプセル化されます。また、UIの観点から、コントロールが相互に影響を与える場合は、とにかくそれらを互いに近づける必要があります。