【问题标题】:How to accept only integers in a WPF textbox [duplicate]如何在 WPF 文本框中仅接受整数 [重复]
【发布时间】:2013-01-26 15:53:24
【问题描述】:

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

【问题讨论】:

  • 你看过 char.IsNumeric 方法吗..?在 Key Press 或 Key Down 事件上检查这个..?
  • 是的,我有一条警告消息 keychar is not found
  • 最好显示一些代码 .. 因为您可以使用 KeyEvents 来获得它...如果不是,您可能需要在该字段上设置一个掩码

标签: c# wpf xaml


【解决方案1】:

如果您不想下载 WPF 工具包(它同时具有 IntegerUpDown 控件或 MaskedTextBox),您可以使用 UIElement.PreviewTextInputDataObject.Pasting 事件根据Masked TextBox In WPF 上的这篇文章改编自实现它.

这是您要在窗口中放置的内容:

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

【讨论】:

  • 会试试这个。谢谢!
【解决方案2】:
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;
    }
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多