首页 > Windows开发 > 详细

wpf怎么让Textbox只能输入数字?

时间:2014-12-10 12:20:01      阅读:688      评论:0      收藏:0      [点我收藏+]

在网上看了好多,发现要么太啰嗦,要么不够完美:其实只需要两步:

1.禁掉输入法:

<Window x:Class="WpfModelViewApplication1.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
    Title="Main Window" Height="400" Width="800">
        <Grid x:Name="grid1">
            <TextBox x:Name="tb" Width="100" HorizontalAlignment="Right" Margin="0,164,122,128"  input:InputMethod.IsInputMethodEnabled="False"/>
        </Grid>
</Window>
第二步 采用正则表达式:

<Window x:Class="WpfModelViewApplication1.Views.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
    Title="Main Window" Height="400" Width="800">

 <Grid x:Name="grid1">
            <TextBox x:Name="tb" Width="100" HorizontalAlignment="Right" Margin="0,164,122,128" PreviewTextInput="tb_PreviewTextInput" input:InputMethod.IsInputMethodEnabled="False"/>
        </Grid>

</Window>

cs后台代码:

        

//using System.Text.RegularExpressions;

        private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)

        {

            Regex re = new Regex("[^0-9.-]+");

            e.Handled = re.IsMatch(e.Text);

        }

 

wpf怎么让Textbox只能输入数字?

原文:http://www.cnblogs.com/lijinping321/p/4154968.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!