<Window x:Class="KeyPressTest1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:KeyPressTest1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="textbox_1" HorizontalAlignment="Center" Height="23" TextWrapping="NoWrap" VerticalAlignment="Center" Width="120" PreviewTextInput="Input_Test"/>
</Grid>
</Window>
C#
1using System.Windows;
2using System.Windows.Input;
3
4
5namespace KeyPressTest1
6{
7 /// <summary>
8 /// MainWindow.xaml の相互作用ロジック
9 /// </summary>
10 public partial class MainWindow : Window
11 {
12 public MainWindow()
13 {
14 InitializeComponent();
15 }
16
17 private void Input_Test(object sender, TextCompositionEventArgs e)
18 {
19 bool cut = false;
20 string check = "0123456789,\b";
21
22 if (check.Contains(e.Text) == false)
23 {
24 cut = true;
25 }
26
27 e.Handled = cut;
28 }
29 }
WPFで考えました。バックスペースとカンマを許容します。
keypressだけで使える方法です。
formバージョン
C#
1using System.Linq;
2using System.Windows.Forms;
3
4namespace KeyPressTest2
5{
6 public partial class Form1 : Form
7 {
8 public Form1()
9 {
10 InitializeComponent();
11 }
12
13 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
14 {
15 bool cut = false;
16 string check = "0123456789,\b";
17
18 if (check.Contains(e.KeyChar) == false)
19 {
20 cut = true;
21 }
22
23 e.Handled = cut;
24 }
25 }
26}
参考にしたページ
WPF:数値しか受け付けないTextBox
退会済みユーザー
2017/05/16 12:59