<分区>
你知道如何限制用户在文本框中输入,这个文本框只接受整数吗?顺便说一句,我正在为 Windows 8 开发。我已经尝试过从 SO 和 Google 搜索的内容,但它不起作用,
<分区>
你知道如何限制用户在文本框中输入,这个文本框只接受整数吗?顺便说一句,我正在为 Windows 8 开发。我已经尝试过从 SO 和 Google 搜索的内容,但它不起作用,
最佳答案
如果您不想下载 WPF 工具包(它既有 IntegerUpDown 控件也有 MaskedTextBox),您可以根据 Masked TextBox In WPF 上的这篇文章自行实现它使用 UIElement.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"
<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/