现在的位置: 首页 > 综合 > 正文

WPF中TextBox限制输入方法

2011年08月26日 ⁄ 综合 ⁄ 共 447字 ⁄ 字号 评论关闭

用PreviewKeyDown事件和KeyEventArgs.Handled 来实现

示例:限制了只能输入1和退格键

XAML

<TextBox HorizontalAlignment="Left" Margin="0,60,0,0" Name="textBox1" Width="120" Height="22" VerticalAlignment="Top"  PreviewKeyDown="textBox1_PreviewKeyDown" />

 

C#

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            
if (e.Key != Key.D1 && e.Key != Key.Back && e.Key !=Key.NumPad1)
            {
                e.Handled 
= true;
            }
        }

 

 

抱歉!评论已关闭.