2013-02-11 89 views
1

你知道如何限制用户在文本框中的输入,这个文本框只接受整数吗?顺便说一下,我正在为Windows 8开发。我尝试过从搜索结果和谷歌搜索的内容,但它不起作用,如何只接受WPF文本框中的整数

+0

有你看着char.IsNumeric方法..?在按键或按键事件中检查。 – MethodMan 2013-02-11 14:26:33

+0

是我有一个警告消息keychar没有被发现 – Dunkey 2013-02-11 15:07:14

+0

更好地显示一些代码..因为有KeyEvents,你可以用它来获得...如果不是,也许你需要在该字段 – MethodMan 2013-02-11 15:40:45

回答

4

如果你不想下载WPF工具包(它有两个IntegerUpDown控制或MaskedTextBox中)。你可以自己实现在本article

看到这里,你会放什么东西在自己的窗口:

<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#:

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); }); 
    } 
} 
+0

设置一个掩码将尝试这一点。谢谢! – Dunkey 2013-02-11 15:07:42

5
public class IntegerTextBox : TextBox 
{ 
    protected override void OnTextChanged(TextChangedEventArgs e) 
    { 
     base.OnTextChanged(e); 

     Text = new String(Text.Where(c => Char.IsDigit(c)).ToArray()); 
     this.SelectionStart = Text.Length; 
    } 
}