如何只接受WPF文本框中的整数

时间:2013-02-11 14:22:53

标签: c# wpf xaml

您知道如何在文本框中限制用户输入,此文本框只接受整数吗?顺便说一下,我正在为Windows 8开发。我尝试过从SO和谷歌搜索的内容,但它没有用,

4 个答案:

答案 0 :(得分:6)

如果您不想下载WPF ToolKit(同时包含IntegerUpDown控件或MaskedTextBox),您可以使用Masked TextBox In WPFUIElement.PreviewTextInput上自行实现本文的改编。 DataObject.Pasting事件。

以下是您要放在窗口中的内容:

<Window x:Class="WpfApp1.MainWindow" Title="MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Vertical" Width="100" Height="100"  HorizontalAlignment="Left" VerticalAlignment="Top">

        <TextBlock Name="NumericLabel1"  Text="Enter Value:"  />
        <TextBox   Name="NumericInput1" 
                   PreviewTextInput="MaskNumericInput" 
                   DataObject.Pasting="MaskNumericPaste"  />
    </StackPanel>
</Window>

然后在代码隐藏中实现C#:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MaskNumericInput(object sender, TextCompositionEventArgs e)
    {
        e.Handled = !TextIsNumeric(e.Text);
    }

    private void MaskNumericPaste(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(typeof(string)))
        {
            string input = (string)e.DataObject.GetData(typeof(string));
            if (!TextIsNumeric(input)) e.CancelCommand();
        }
        else
        {
            e.CancelCommand();
        }
    }

    private bool TextIsNumeric(string input)
    {
        return input.All(c => Char.IsDigit(c) || Char.IsControl(c));
    }
}

答案 1 :(得分:6)

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;
    }
}

答案 2 :(得分:1)

在最原始级别,您可以截取KeyUp事件或TextChanged以查看正在添加的字符,如果无法将其解析为Int,则将其删除。

同时检查 - Only accept digits for textboxMasking Textbox to accept only decimals

答案 3 :(得分:0)

您可以使用整数向下控制。 WPF工具包中有一个可以解决这个问题:

https://wpftoolkit.codeplex.com/wikipage?title=IntegerUpDown

相关问题