برای اطمینان از اینکه TextBox در WPF فقط ورودی رقمی را می پذیرد، می توانید رویداد PreviewTextInput را مدیریت کنید و از ویژگی IsInputValid برای فیلتر کردن کاراکترهای غیر عددی استفاده کنید. در اینجا نحوه رسیدن به این هدف آورده شده است:

متد: استفاده از رویداد PreviewTextInput
1. TextBox را در XAML تعریف کنید:
یک TextBox در MainWindow.xaml خود اضافه کنید و رویداد PreviewTextInput را مدیریت کنید:
<Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBox Width="200" Height="30" Margin="10" PreviewTextInput="TextBox_PreviewTextInput"/> </Grid> </Window>
2. رویداد PreviewTextInput را در Code-Behind مدیریت کنید:
کنترل کننده رویداد را برای فیلتر کردن نویسههای غیر رقمی در MainWindow.xaml.cs اضافه کنید:
using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace YourNamespace { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { // Use a regular expression to check if the input is a digit e.Handled = !IsTextAllowed(e.Text); } private static bool IsTextAllowed(string text) { // Regular expression to allow only digits Regex regex = new Regex("[^0-9]+"); return !regex.IsMatch(text); } } }
توضیح
1. رویداد PreviewTextInput: رویداد PreviewTextInput هر زمان که کاربر کاراکتری را در TextBox تایپ میکند فعال میشود. با مدیریت این رویداد، می توانید کاراکترهای ناخواسته را قبل از اضافه شدن به TextBox فیلتر کنید.
2. متد IsTextAllowed: متد IsTextAllowed از یک عبارت منظم ([^0-9]+) استفاده می کند تا بررسی کند که آیا متن ورودی فقط دارای اعداد است یا خیر. اگر متن حاوی نویسه های غیر رقمی باشد، متد false را برمی گرداند.
3. e.Handled: با تنظیم e.Handled روی true، می توانید از پردازش ورودی جلوگیری کنید و کاراکترهای غیر رقمی را به طور موثر فیلتر کنید.
نکات اضافی
Paste Handling: برای رسیدگی به مواردی که کاربران ممکن است متن غیر رقمی را جایگذاری کنند، میتوانید رویداد DataObject.Pasting را نیز مدیریت کنید:
using System.Windows.Data; ... public MainWindow() { InitializeComponent(); DataObject.AddPastingHandler(MyTextBox, OnPaste); } private void OnPaste(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(string))) { string text = (string)e.DataObject.GetData(typeof(string)); if (!IsTextAllowed(text)) { e.CancelCommand(); } } else { e.CancelCommand(); } }
این رویکرد تضمین میکند که TextBox فقط ورودی رقمی را میپذیرد، چه هنگام تایپ و چه هنگام چسباندن.