[WPF] TextBox 숫자값만 입력받기.

2024. 5. 17. 17:07프로그래밍/C#

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
  if( !((Key.D0 <= e.key && e.key <= Key.D9)
    || (Key.NumPad0 <= e.Key && e.Key <= Key.NumPad9)
    || e.Key == Key.Back) )
    { e.Handled = true; }
}

- Key.D0 ~ Key.D9 : qwer 키패드 위의 숫자
- Key.NumPad0 ~ Key.NumPad9 : 키보드 우측 숫자키
- Key.Back : BackSpace

- e.Handled = true : 더이상 Route 되지 않도록 변경

* HandledEventArgs 설명
[Properties]
- Handled : 이벤트 처리기가 이벤트를 완전히 처리했는지 시스템이 자체 처리를 계속해야 하는지 여부를 나타내는 값을 가져오거나 설정한다.



* 소스참고
https://www.gigong.io/2022/04/17/WPF-TextBox-input-only-number-input-filter

WPF TextBox 숫자만 입력 하기(입력 필터) | GiGong Blog

0. 시작 WPF에서 TextBox로 입력을 받을 때 숫자 혹은 특정 문자만 입력하게 해야할 때가 있습니다. 그 방법에 대해 알아보겠습니다.

www.gigong.io


* 이벤트핸들러 참고문서
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.handledeventargs?view=net-8.0

HandledEventArgs Class (System.ComponentModel)

Provides data for events that can be handled completely in an event handler.

learn.microsoft.com

'프로그래밍 > C#' 카테고리의 다른 글

[WPF] TreeView SelectedItem Clear  (0) 2024.05.28
[C#] Stack 사용  (0) 2023.03.26
[C#] int 배열 사용  (0) 2023.03.23
[C#] String 배열 다루기  (0) 2023.03.23
string.Equals 사용시 Null 처리  (0) 2023.03.17