如何接受一个WPF文本框仅整数 [英] How to accept only integers in a WPF textbox
本文介绍了如何接受一个WPF文本框仅整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你知道如何限制在文本框用户输入,这个文本框只接受整?顺便说一句,我开发的Windows 8,我试过我从SO和谷歌搜索,但它不工作,
Do you know how to restrict user input in textbox, this textbox only accepts integer? By the way I'm developing for Windows 8. I've tried what I searched from SO and from Google but it's not working,
推荐答案
如果你不想下载WPF工具包(其中有两个IntegerUpDown控制或MaskedTextBox中)。您可以自己实现它在这个文章看到
If you don't want to download the wpf toolkit (which has both the IntegerUpDown control or a MaskedTextBox). You can implement it yourself as seen in this article
下面是你放什么在你的窗口:
Here's what you would put in your window:
<Window x:Class="MaskedTextBoxInWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Masked Text Box In WPF" Height="350" Width="525">
<Grid>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="98,80,0,0" Name="textBlock1" Text="Enter Value:" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,80,0,0" Name="textBoxValue" PreviewTextInput="textBoxValue_PreviewTextInput" DataObject.Pasting="textBoxValue_Pasting" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
,然后实现在你的代码隐藏在C#中:
And then implement the C# in your codebehind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void textBoxValue_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !TextBoxTextAllowed(e.Text);
}
private void textBoxValue_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String Text1 = (String)e.DataObject.GetData(typeof(String));
if (!TextBoxTextAllowed(Text1)) e.CancelCommand();
}
else e.CancelCommand();
}
private Boolean TextBoxTextAllowed(String Text2)
{
return Array.TrueForAll<Char>(Text2.ToCharArray(),
delegate(Char c) { return Char.IsDigit(c) || Char.IsControl(c); });
}
}
这篇关于如何接受一个WPF文本框仅整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文