WPF中TextBox失去焦点事件

限制TextBox只能输入整数,而且整数的数值范围为0-100。如果输入101后,弹窗提示输入超限


MainWindow.xaml

xml 复制代码
 <TextBox x:Name="textBox1" TextWrapping="Wrap" Text="TextBox" Width="120" Height="50" LostFocus="myTextBox_LostFocus"/>

MainWindow.xaml.cs

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NumRange2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void myTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            // 在这里添加你的处理代码
            string textVal = textBox1.Text;
            try
            {
                int numVal = int.Parse(textVal);
                if (numVal > 100 || numVal < 0)
                {
                    MessageBox.Show("输入超限");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("请输入一个整数");
            }
            
        }
    }
}
相关推荐
是木子啦2 小时前
wpf passwordbox控件 光标移到最后
c#·wpf
The Sheep 20232 小时前
wpf 命令理解
wpf
布伦鸽2 小时前
C# WPF DataGrid使用Observable<Observable<object>类型作为数据源
开发语言·c#·wpf
分布式存储与RustFS15 小时前
告别复杂配置:用Milvus、RustFS和Vibe Coding,60分钟DIY专属Chatbot
wpf·文件系统·milvus·对象存储·minio·rustfs·vibe
攻城狮CSU1 天前
WPF 绑定机制实现原理
wpf
攻城狮CSU1 天前
WPF 之数据绑定一(Data Binding)
wpf
wuty0072 天前
记录一下 WPF进程 SendMessage 发送窗口消息进行进程间通信,存在进程权限无法接受消息的问题
wpf·进程间通信·sendmessage·进程权限
c#上位机2 天前
wpf之ToggleButton控件
c#·wpf
浪扼飞舟2 天前
WPF用户控件和依赖属性
wpf
c#上位机3 天前
wpf之MVVM中只读属性更新界面
c#·wpf·mvvm