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

标签 c# wpf xaml

<分区>

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

最佳答案

如果您不想下载 WPF 工具包(它既有 IntegerUpDown 控件也有 MaskedTextBox),您可以根据 Masked TextBox In 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" 
                   <b>PreviewTextInput="MaskNumericInput"</b> 
                   <b>DataObject.Pasting="MaskNumericPaste"</b>  />
    </StackPanel>
</Window>

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

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

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

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

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

关于c# - 如何只接受 WPF 文本框中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14813960/

相关文章:

c# - Entity Framework 和数据库连接

c# - 动态文本框在asp.net中添加按钮单击和数据 session

C#、LINQ、SQL : Compound columns

c# - 启动第二个实例时 Adob​​e Reader 进程失败

WPF:文本框文本未更新

c# - 命名用户控件。习俗?

WPF 玻璃窗口后备?

c# - 如何使包含 ItemsControl 的 WPF 网格具有相同大小的列

silverlight - 为 Dots and Boxes 游戏绘制网格的最佳方法是什么? (银光)

wpf - 当 TextBox 获得焦点时,UserControl 中的 KeyBinding 不起作用