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

Dun*_*key 6 c# wpf xaml

你知道如何在文本框中限制用户输入,这个文本框只接受整数吗?顺便说一句,我正在为Windows 8开发.我尝试过从SO和Google搜索的内容,但是它没有用,

Kyl*_*Mit 8

如果您不想下载WPF ToolKit(它同时包含IntegerUpDown控件或MaskedTextBox),您可以使用和事件自行实现它,如本文中关于Masked TextBox在WPF中的改编.UIElement.PreviewTextInputDataObject.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>
Run Code Online (Sandbox Code Playgroud)

然后在代码隐藏中实现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));
    }
}
Run Code Online (Sandbox Code Playgroud)


Nat*_*yer 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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Gra*_*ush 0

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

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