22. 윈도우 계산기 - 숫자 입력 구현

01. 숫자 입력 버튼 7, 8, 9 구현
01.1 버튼 7, 버튼 8, 버튼 9 입력을 구현합니다.

01.2 "버튼 7" 컨트롤의 이벤트를 생성하기 위해 버튼 컨트롤을 더블클릭합니다.

01.3 "버튼 7" 컨트롤의 이벤트가 Code behind에 sevenButton_Click 이벤트가 자동 생성됩니다.

01.4 "버튼 7"을 누르면, 출력 레이블에 입력되도록 C# 소스코드를 구현합니다.

❹ 버튼이 클릭되었을 때, 실행될 함수의 로직은, 결과를 출력하는 레이블에 값이 0이라면, 해당 버튼의 숫자를 출력하고, 기존에 값이 입력되어 있다면, 기존 값 뒤에 버튼의 값을 추가하여 보여줍니다.
if (resultLabel.Content.ToString() == "0") { resultLabel.Content = "7"; } else { resultLabel.Content = $"{resultLabel.Content}7"; }
01.4 "버튼 8", "버튼 9" 도 동일한 작업을 진행합니다.

01.5 실행하여, 동작을 확인합니다.
02. 숫자 입력 버튼 이벤트 핸들러 개선(1)
02.1 문제 인식
위 숫자 버튼의 입력을 구현하는 과정은 동일하게 9번 반복 구현되어야 합니다.
숫자 버튼 9개는 모두 동일한 동작을 수행합니다.
= 함수의 로직이 같습니다.
= 데이터만 다릅니다.
= 하나의 함수로 수정 가능합니다.
02.2 이벤트 로직 수정

private void NumberButton_Click(object sender, RoutedEventArgs e) { int selectedBtnValue = 0; if (sender == zeroButton) selectedBtnValue = 0; else if (sender == oneButton) selectedBtnValue = 1; else if (sender == twoButton) selectedBtnValue = 2; else if (sender == threeButton) selectedBtnValue = 3; else if (sender == fourButton) selectedBtnValue = 4; else if (sender == fiveButton) selectedBtnValue = 5; else if (sender == sixButton) selectedBtnValue = 6; else if (sender == sevenButton) selectedBtnValue = 7; else if (sender == eightButton) selectedBtnValue = 8; else if (sender == nineButton) selectedBtnValue = 9; if (resultLabel.Content.ToString() == "0") { resultLabel.Content = $"{selectedBtnValue}"; } else { resultLabel.Content = $"{resultLabel.Content}{selectedBtnValue}"; } }
02.3 UI 컨트롤의 참조 이벤트 수정

❶ 각각의 버튼은 각각의 이벤트 핸들러 함수로 구현되어 있습니다.

❷ Code behind에 구현한 이벤트 핸들러 함수로 참조를 변경합니다.
02.4 실행하여, 동작을 확인합니다.
03. 숫자 입력 버튼 이벤트 핸들러 개선(2)
03.1

private void NumberButton_Click2(object sender, RoutedEventArgs e) { //Sender 객체가 버튼인 경우, 버튼 객체에 .(닷 연산자)를 사용해 컨텐츠 속성을 가져와 int로 변환 후 저장 //_ diacard 변수는 값을 반환하더라도, 사용할 일이 없기에 안전하게 버려도 됨을 나타낸다. _ = int.TryParse(((Button)sender).Content.ToString(), out int selectedBtnValue); if (resultLabel.Content.ToString() == "0") { resultLabel.Content = $"{selectedBtnValue}"; } else { resultLabel.Content = $"{resultLabel.Content}{selectedBtnValue}"; } }

❷ Code behind에 구현한 이벤트 핸들러 함수로 참조를 변경합니다.
03.2 실행하여, 동작을 확인합니다.
04. 실행 결과 확인
댓글을 사용할 수 없습니다.