wpf 只能输入int类型的文本框

我做的这个文本框,可设置最大值,最小值,有失去焦点事件的话,失去焦点文本框里的数字是你上次填的数字,避免数据为空的情况。

有失去焦点事件

cs 复制代码
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;

namespace 项目名
{
    public class IntegerTextBox : TextBox
    {
        public bool isMouseEntered = false;

        public string PreviousText
        {
            get { return (string)GetValue(PreviousTextProperty); }
            set { SetValue(PreviousTextProperty, value); }
        }
        public static readonly DependencyProperty PreviousTextProperty =
            DependencyProperty.Register("PreviousText", typeof(string), typeof(IntegerTextBox), new PropertyMetadata(string.Empty));

        public string HistoryText
        {
            get { return (string)GetValue(HistoryTextProperty); }
            set { SetValue(HistoryTextProperty, value); }
        }
        public static readonly DependencyProperty HistoryTextProperty = DependencyProperty.Register("HistoryText", typeof(string), typeof(IntegerTextBox), new PropertyMetadata(string.Empty));

        public int? MinValue
        {
            get { return (int?)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }

        public static readonly DependencyProperty MinValueProperty =
            DependencyProperty.Register("MinValue", typeof(int?), typeof(IntegerTextBox));

        public int MaxValue
        {
            get { return (int)GetValue(MaxValueProperty); }
            set { SetValue(MaxValueProperty, value); }
        }

        public static readonly DependencyProperty MaxValueProperty =
        DependencyProperty.Register("MaxValue", typeof(int), typeof(IntegerTextBox), new PropertyMetadata(int.MaxValue));

        public static bool GetIsEnabled(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsGotFocusProperty);
        }

        public static void SetIsEnabled(DependencyObject obj, bool value)
        {
            obj.SetValue(IsGotFocusProperty, value);
        }

        public bool IsNeedLoseFucos
        {
            get { return (bool)GetValue(IsNeedLoseFucosvProperty); }
            set { SetValue(IsNeedLoseFucosvProperty, value); }
        }
        public static readonly DependencyProperty IsNeedLoseFucosvProperty =
            DependencyProperty.RegisterAttached("IsNeedLoseFucos", typeof(bool), typeof(IntegerTextBox), new PropertyMetadata(true));

        public bool IsGotFocus
        {
            get { return (bool)GetValue(IsGotFocusProperty); }
            set { SetValue(IsGotFocusProperty, value); }
        }
        public static readonly DependencyProperty IsGotFocusProperty =
            DependencyProperty.RegisterAttached("IsGotFocus", typeof(bool), typeof(IntegerTextBox), new PropertyMetadata(false));

        static IntegerTextBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(IntegerTextBox), new FrameworkPropertyMetadata(typeof(IntegerTextBox)));
        }

        public IntegerTextBox()
        {
            LostFocus += IntegerTextBox_LostFocus;
            PreviewTextInput += IntegerTextBox_PreviewTextInput;
        }

        private void IntegerTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Text = Text.Trim();
            string txt = Text + e.Text;
            if (txt.Length > 1 && txt.StartsWith('0'))
            {
                Text = Text.Substring(1);
            }
            if (!int.TryParse(txt, out int value))
            {
                if (!string.IsNullOrWhiteSpace(Text))
                {
                    var index = Text.IndexOf(e.Text);
                    if (index > -1) { Text = Text.Remove(index); }

                    SelectionStart = Text.Length + e.Text.Length;
                }
                e.Handled = true; // 阻止输入非数字字符
            }
            //else if (value < MinValue && value.ToString().Length == MinValue.ToString().Length)
            //{
            //    Text = MinValue.ToString(); // 将文本框的值设置为最小值
            //    SelectionStart = Text.Length + e.Text.Length;
            //    e.Handled = true; // 阻止输入超出取值范围的数字
            //}
            else if (value > MaxValue)
            {
                Text = MaxValue.ToString(); // 将文本框的值设置为最大值
                SelectionStart = Text.Length + e.Text.Length;
                e.Handled = true; // 阻止输入超出取值范围的数字
            }
            else
            {
                Text = value.ToString();
                SelectionStart = Text.Length + e.Text.Length;
                e.Handled = true;
            }
            SelectionStart = Text.Length + e.Text.Length;
            HistoryText = Text;
        }

        private void IntegerTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            IsGotFocus = false;

            Text = Text.Trim();
            if (string.IsNullOrEmpty(Text))
            {
                if (!string.IsNullOrEmpty(HistoryText) && int.TryParse(HistoryText, out int history) && history > MinValue)
                {
                    Text = HistoryText;
                }
                else if (!string.IsNullOrEmpty(PreviousText))
                {
                    Text = PreviousText;
                }
                else if (MinValue is not null)
                {
                    Text = MinValue.Value.ToString();
                }
            }
            else
            {
                if (int.TryParse(Text, out int num))
                {
                    if (num < MinValue)
                    {
                        if (!string.IsNullOrEmpty(HistoryText) && int.TryParse(HistoryText, out int history) && history > MinValue)
                        {
                            Text = HistoryText;
                        }
                        else
                        {
                            Text = MinValue.ToString();
                        }
                    }
                    else if (num > MaxValue)
                    {
                        if (!string.IsNullOrEmpty(HistoryText) && int.TryParse(HistoryText, out int history) && history < MaxValue)
                        {
                            Text = HistoryText;
                        }
                        else if (!string.IsNullOrEmpty(PreviousText))
                        {
                            Text = PreviousText;
                        }
                        else
                        {
                            Text = MaxValue.ToString();
                        }
                    }
                }
            }
            SelectionStart = Text.Length;
        }
    }
}

没有失去焦点事件:

cs 复制代码
public class IntegerTextBoxNoLF : TextBox
    {
        public bool isMouseEntered = false;

        public string PreviousText
        {
            get { return (string)GetValue(PreviousTextProperty); }
            set { SetValue(PreviousTextProperty, value); }
        }
        public static readonly DependencyProperty PreviousTextProperty =
            DependencyProperty.Register("PreviousText", typeof(string), typeof(IntegerTextBoxNoLF), new PropertyMetadata(string.Empty));

        public string HistoryText
        {
            get { return (string)GetValue(HistoryTextProperty); }
            set { SetValue(HistoryTextProperty, value); }
        }
        public static readonly DependencyProperty HistoryTextProperty = DependencyProperty.Register("HistoryText", typeof(string), typeof(IntegerTextBoxNoLF), new PropertyMetadata(string.Empty));

        public int? MinValue
        {
            get { return (int?)GetValue(MinValueProperty); }
            set { SetValue(MinValueProperty, value); }
        }

        public static readonly DependencyProperty MinValueProperty =
            DependencyProperty.Register("MinValue", typeof(int?), typeof(IntegerTextBoxNoLF));

        public int MaxValue
        {
            get { return (int)GetValue(MaxValueProperty); }
            set { SetValue(MaxValueProperty, value); }
        }

        public static readonly DependencyProperty MaxValueProperty =
        DependencyProperty.Register("MaxValue", typeof(int), typeof(IntegerTextBoxNoLF), new PropertyMetadata(int.MaxValue));

        public static bool GetIsEnabled(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsGotFocusProperty);
        }

        public static void SetIsEnabled(DependencyObject obj, bool value)
        {
            obj.SetValue(IsGotFocusProperty, value);
        }

        public bool IsNeedLoseFucos
        {
            get { return (bool)GetValue(IsNeedLoseFucosvProperty); }
            set { SetValue(IsNeedLoseFucosvProperty, value); }
        }
        public static readonly DependencyProperty IsNeedLoseFucosvProperty =
            DependencyProperty.RegisterAttached("IsNeedLoseFucos", typeof(bool), typeof(IntegerTextBoxNoLF), new PropertyMetadata(true));

        public bool IsGotFocus
        {
            get { return (bool)GetValue(IsGotFocusProperty); }
            set { SetValue(IsGotFocusProperty, value); }
        }
        public static readonly DependencyProperty IsGotFocusProperty =
            DependencyProperty.RegisterAttached("IsGotFocus", typeof(bool), typeof(IntegerTextBoxNoLF), new PropertyMetadata(false));


        static IntegerTextBoxNoLF()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(IntegerTextBoxNoLF), new FrameworkPropertyMetadata(typeof(IntegerTextBoxNoLF)));
        }

        public IntegerTextBoxNoLF()
        {
            PreviewTextInput += IntegerTextBox_PreviewTextInput;
            //PreviewMouseLeftButtonDown += IntegerTextBox_PreviewMouseLeftButtonDown;
        }

        private void IntegerTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Text = Text.Trim();
            string txt = Text + e.Text;
            if (txt.Length > 1 && txt.StartsWith('0'))
            {
                Text = Text.Substring(1);
            }
            if (!int.TryParse(txt, out int value))
            {
                if (!string.IsNullOrWhiteSpace(Text))
                {
                    var index = Text.IndexOf(e.Text);
                    if (index > -1) { Text = Text.Remove(index); }

                    SelectionStart = Text.Length + e.Text.Length;
                }
                e.Handled = true; // 阻止输入非数字字符
            }
            else if (value < MinValue && value.ToString().Length == MinValue.ToString().Length)
            {
                Text = MinValue.ToString(); // 将文本框的值设置为最小值
                SelectionStart = Text.Length + e.Text.Length;
                e.Handled = true; // 阻止输入超出取值范围的数字
            }
            else if (value > MaxValue)
            {
                Text = MaxValue.ToString(); // 将文本框的值设置为最大值
                SelectionStart = Text.Length + e.Text.Length;
                e.Handled = true; // 阻止输入超出取值范围的数字
            }
            else
            {
                Text = value.ToString();
                SelectionStart = Text.Length + e.Text.Length;
                e.Handled = true;
            }
            SelectionStart = Text.Length + e.Text.Length;
            HistoryText = Text;
        }

        private void IntegerTextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Text = string.Empty;
            Focusable = true;
            Focus();
            IsGotFocus = true;
        }
    }

调用:

cs 复制代码
<local:IntegerTextBox MinValue="0" MaxValue="59" TextAlignment="Center" Width="120" Height="48" Text="{Binding Program.VibrationHour,TargetNullValue={x:Static sys:String.Empty}}" VerticalContentAlignment="Center" InputMethod.IsInputMethodEnabled="False" />
相关推荐
极客智造16 小时前
深入解析 WPF 中的 DataTemplateSelector:动态模板选择的艺术
wpf
极客智造16 小时前
WPF 高级 UI 定制:深入解析 VisualStateManager 与 Adorner
wpf
LateFrames2 天前
使用 Winform / WPF / WinUI3 / Electron 实现异型透明窗口
javascript·electron·wpf·winform·winui3
ifeng09182 天前
HarmonyOS实战项目:AI健康助手(影像识别与健康分析)
人工智能·华为·wpf·harmonyos
Aevget2 天前
界面控件Telerik UI for WPF 2025 Q3亮点 - 集成AI编码助手
人工智能·ui·wpf·界面控件·ui开发·telerik
张人玉2 天前
WPF 数据绑定与转换器详解
c#·wpf·light
主宰者2 天前
WPF CalcBinding简化判断逻辑
c#·.net·wpf
Aevget2 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(五)
wpf·界面控件·devexpress·ui开发·.net 10
张人玉3 天前
C#WPF UI路由事件:事件冒泡与隧道机制
ui·c#·wpf
Aevget4 天前
DevExpress WPF v25.2新功能预览 - 支持将JetBrains Rider与报表设计器集成
.net·wpf·界面控件·devexpress·ui开发