2013-02-11 60 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; 
    } 
} 
相關問題