일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- commit
- csharp
- Microsoft
- Binding
- Process
- IValueConverter
- WPF
- programmers
- string
- Coding
- 코딩테스트
- mysql
- Visual Studio
- windows10
- C#
- .net
- log
- chashtag
- tls
- logging
- dotNET
- Github
- algorithm
- git
- nullable
- File
- coding-test
- convert
- windows
- ListView
Archives
- Today
- Total
CHashtag
[C#] [WPF] TextBox 숫자만 입력받는 법 본문
반응형
안녕하세요.
오늘은 WPF에서 TextBox를 사용할 때 숫자만 입력받는 방법에 대해 알아보도록 하겠습니다.
방법이 간단하여 바로 코드로 설명해드리도록 하겠습니다.
PreviewTextInput Event는 Text가 변경되었을 때 값이 반영되기 전에 먼저 들어오는 이벤트입니다.
여기서 e.Handled값을 이용하여 값 변경을 허용할지 말지를 결정짓게 되는겁니다.
따라서 Regex를 이용하여 숫자일 때에만 수정이 가능하게 구현하였습니다.
<!-- MainWindow.xaml -->
<TextBox PreviewTextInput="TextBox_PreviewTextInput" Text="{Binding Text}"/>
// MainWindow.xaml.cs
using System.Text.RegularExpressions;
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
참고 링크
How do I get a TextBox to only accept numeric input in WPF?
I'm looking to accept digits and the decimal point, but no sign. I've looked at samples using the NumericUpDown control for Windows Forms, and this sample of a NumericUpDown custom control from
stackoverflow.com
감사합니다.
반응형
'C# > WPF' 카테고리의 다른 글
[C#/WPF] Converter사용하여 bool 반대값 binding하기 (0) | 2023.02.20 |
---|---|
[C# WPF] 다른 Control Property Binding (다른 컨트롤 속성 바인딩) (5) | 2021.12.03 |
[C#] [WPF] TextBox의 실시간 Binding(바인딩) (0) | 2021.09.16 |
[C#] [WPF] ComboBox Converter 사용방법 (0) | 2021.07.24 |
[C# WPF] DateTimePicker 사용방법 (시분초까지 선택하는법) (0) | 2021.07.19 |