精华内容
下载资源
问答
  • WPF 数字输入框

    千次阅读 2019-05-28 11:27:41
    一个简单的TextBox,数字输入控制中间件

    直接上代码:
    .xaml文件:一个输入框

                    <TextBox 
                Name="test"             
     DataObject.Pasting="Volt_Pasting" PreviewKeyDown="Volt_PreviewKeyDown" InputMethod.IsInputMethodEnabled="False"
                       PreviewTextInput="Volt_PreviewTextInput"                        
        Style="{StaticResource MaterialDesignFilledTextFieldTextBox}"
        VerticalAlignment="Bottom"
        AcceptsReturn="True"
        TextWrapping="Wrap"
        MaxWidth="110"    
        MaxHeight="60"
        MaxLength="8"
        materialDesign:HintAssist.Hint="test)" />
    

    .cs 文件

            private void Volt_Pasting(object sender, DataObjectPastingEventArgs e)
            {
                Dat_input_box.TextBox_Pasting(sender, e);
            }
    
    
    
            private void Volt_PreviewKeyDown(object sender, KeyEventArgs e)
            {
                Dat_input_box.TextBox_OnPreviewKeyDown(e);
            }
    
    
    
            private void Volt_PreviewTextInput(object sender, TextCompositionEventArgs e)
            {
                Dat_input_box.TextBox_PreviewTextInput(sender, e);
            }
    

    .cs封装库

    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;
    using System.Text.RegularExpressions;
    
    namespace Controls.Tools
    {
        class Dat_input_box
        {
            //限制非法字符输入,只允许输入数字和小数点
            public static void TextBox_PreviewTextInput(object sender,
                TextCompositionEventArgs e)
            {
                var textBox = sender as TextBox;
                //这是对中文值的判断
                if (textBox == null) return;
                //if (Regex.IsMatch(textBox.Text, @"[\u4e00-\u9fbb]+$"))
                //{
                //   textBox.Text = "";
                //   e.Handled = true;
                //  return;
                //}
                //匹配只能输入一个小数点的浮点数
                Regex numbeRegex = new Regex("^[-]?\\d+[.]?\\d*$");
                Regex zeroRegex = new Regex("^[0]+[0-9]+$");
                e.Handled =
                        !numbeRegex.IsMatch(
                            textBox.Text.Insert(
                                textBox.SelectionStart, e.Text))
                                || zeroRegex.IsMatch(
                            textBox.Text.Insert(
                                textBox.SelectionStart, e.Text));
                textBox.Text = textBox.Text.Trim();
            }
    
            /// <summary>
            /// 键盘输入值事件(可以小键盘上的数字键和英文输入状态下的句点键盘)
            /// </summary>
            /// <param name="e"></param>
            public static void TextBox_OnPreviewKeyDown(KeyEventArgs e)
            {
                if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 &&
                     e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                    ||
                    (e.Key >= Key.D0 && e.Key <= Key.D9 &&
                     e.KeyboardDevice.Modifiers != ModifierKeys.Shift) ||
                    e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right ||
                    e.Key == Key.Enter || e.Key == Key.Decimal ||
                    e.Key == Key.OemPeriod)
                {
                    if (e.KeyboardDevice.Modifiers != ModifierKeys.None)
                    {
                        e.Handled = false;
                    }
                }
                else
                {
                    e.Handled = true;
                }
            }
    
            /// <summary>
            ///  禁止粘贴
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public static void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
            {
                if (e.DataObject.GetDataPresent(typeof(String)))
                {
                    String text = (String)e.DataObject.GetData(typeof(String));
                    if (!isNumberic(text))
                    { e.CancelCommand(); }
                }
                else { e.CancelCommand(); }
            }
    
            public static bool isNumberic(string _string)
            {
                if (string.IsNullOrEmpty(_string))
                    return false;
                foreach (char c in _string)
                {
                    if (!char.IsDigit(c))
                        //if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
                        return false;
                }
                return true;
            }
        }
    }
    
    

    附录:
    1、C#正则验证大全 Regex.IsMatch()正则表达式验证

    展开全文
  • WPF数字输入框和IP地址输入框 原文:WPF数字输入框和IP地址输入框数字输入框 简介 在业务中,我们经常需要限制用户的输入,比如限制输入长度,限制只能输入数字等等。限制输入长度WPF内置的TextBox...
    原文: WPF数字输入框和IP地址输入框

    数字输入框

    简介

    在业务中,我们经常需要限制用户的输入,比如限制输入长度,限制只能输入数字等等。限制输入长度WPF内置的TextBox已经帮我们解决了,但是限制输入数字却并未在WPF中内置解决方案。使用第三方的控件又要多增加一个引用,于是决定自己写一个。

    在写的过程中发现需要考虑的问题比较多,比如限制输入法、部分限制输入小数点和负号、限制输入字母和其它符号、粘贴时做特殊处理等等。值得一提的是,将文本绑定到Double型且将UpdateSourceTrigger设为PropertyChanged时,出现了界面上包含小数点,但是通过Text获取的文本却并不包含小数点的情况,猜测原因是因为绑定更新和自动类型转换出现的问题。

    数字输入框提供了设置最小值(可用)、最大值(可用)、精度(小数点后位数)的功能。不合法的按键将会被过滤掉,输入的值小于最小值或者大于最大值时,其输入都将视为无效。

    代码

    代码较简单,且有注释,不再多说。

    namespace YiYan127.WPF.Controls
    {
        using System;
        using System.Globalization;
        using System.Windows;
        using System.Windows.Controls;
        using System.Windows.Input;
    
        /// <summary>
        /// 输入数值的文本框
        /// </summary>
        public class NumbericTextBox : TextBox
        {
            #region Fields
    
            #region DependencyProperty
    
            /// <summary>
            /// 最大值的依赖属性
            /// </summary>
            public static readonly DependencyProperty MaxValueProperty = DependencyProperty.Register(
                "MaxValue",
                typeof(double),
                typeof(NumbericTextBox),
                new PropertyMetadata(double.MaxValue));
    
            /// <summary>
            /// 最小值的依赖属性
            /// </summary>
            public static readonly DependencyProperty MinValueProperty = DependencyProperty.Register(
                "MinValue",
                typeof(double),
                typeof(NumbericTextBox),
                new PropertyMetadata(double.MinValue));
    
            /// <summary>
            /// 精度的依赖属性
            /// </summary>
            public static readonly DependencyProperty PrecisionProperty = DependencyProperty.Register(
                "Precision",
                typeof(ushort),
                typeof(NumbericTextBox),
                new PropertyMetadata((ushort)2));
    
            #endregion DependencyProperty
    
            /// <summary>
            /// 先前合法的文本
            /// </summary>
            private string lastLegalText;
    
            /// <summary>
            /// 是否为粘贴
            /// </summary>
            private bool isPaste;
    
            public event EventHandler<TextChangedEventArgs> PreviewTextChanged;
    
            #endregion Fields
    
            #region Constructor
    
            /// <summary>
            /// 构造函数
            /// </summary>
            public NumbericTextBox()
            {
                this.PreviewTextInput += this.NumbericTextBoxPreviewTextInput;
                this.TextChanged += this.NumbericTextBoxTextChanged;
                this.PreviewKeyDown += this.NumbericTextBox_PreviewKeyDown;
                this.LostFocus += this.NumbericTextBoxLostFocus;
                InputMethod.SetIsInputMethodEnabled(this, false);
    
                this.Loaded += this.NumbericTextBoxLoaded;
            }
    
            #endregion Constructor
    
            #region Properties
    
            /// <summary>
            /// 最大值,可取
            /// </summary>
            public double MaxValue
            {
                get { return (double)this.GetValue(MaxValueProperty); }
                set { this.SetValue(MaxValueProperty, value); }
            }
    
            /// <summary>
            /// 最小值,可取
            /// </summary>
            public double MinValue
            {
                get { return (double)this.GetValue(MinValueProperty); }
                set { this.SetValue(MinValueProperty, value); }
            }
    
            /// <summary>
            /// 精度,即精确到小数点后的位数
            /// </summary>
            public ushort Precision
            {
                get { return (ushort)this.GetValue(PrecisionProperty); }
                set { this.SetValue(PrecisionProperty, value); }
            }
    
            #endregion Properties
    
            protected virtual void OnPreviewTextChanged(TextChangedEventArgs e)
            {
                if (this.PreviewTextChanged != null)
                {
                    this.PreviewTextChanged(this, e);
                }
            }
    
            #region Private Methods
    
            /// <summary>
            /// 处理粘贴的情况
            /// </summary>
            protected virtual void HandlePaste()
            {
                this.isPaste = false;
    
                // 处理符号的标志
                bool handledSybmol = false;
    
                // 处理小数点的标志
                bool handledDot = false;
    
                // 当前位对应的基数
                double baseNumber = 1;
    
                // 转换后的数字
                double number = 0;
    
                // 上一次合法的数字
                double lastNumber = 0;
    
                // 小数点后的位数
                double precision = 0;
                foreach (var c in this.Text)
                {
                    if (!handledSybmol && (c == '-'))
                    {
                        baseNumber = -1;
                        handledSybmol = true;
                    }
    
                    if ((c >= '0') && (c <= '9'))
                    {
                        int digit = c - '0';
                        if (!handledDot)
                        {
                            number = (number * baseNumber) + digit;
                            baseNumber = 10;
                        }
                        else
                        {
                            baseNumber = baseNumber / 10;
                            number += digit * baseNumber;
                        }
    
                        // 正负号必须位于最前面
                        handledSybmol = true;
                    }
    
                    if (c == '.')
                    {
                        // 精度已经够了
                        if (precision + 1 > this.Precision)
                        {
                            break;
                        }
    
                        handledDot = true;
    
                        // 此时正负号不能起作用
                        handledSybmol = true;
                        baseNumber = 0.1;
                        precision++;
                    }
    
                    if ((number < this.MinValue) || (number > this.MaxValue))
                    {
                        this.Text = lastNumber.ToString(CultureInfo.InvariantCulture);
                        this.SelectionStart = this.Text.Length;
                        return;
                    }
    
                    lastNumber = number;
                }
    
                this.Text = number.ToString(CultureInfo.InvariantCulture);
                this.SelectionStart = this.Text.Length;
            }
    
            #endregion Private Methods
    
            #region Overrides of TextBoxBase
    
            #endregion
    
            #region Events Handling
    
            private void NumbericTextBoxLoaded(object sender, RoutedEventArgs e)
            {
                if (this.MinValue > this.MaxValue)
                {
                    this.MinValue = this.MaxValue;
                }
    
                if (string.IsNullOrEmpty(this.Text))
                {
                    double val = (this.MaxValue + this.MinValue) / 2;
                    val = Math.Round(val, this.Precision);
    
                    this.Text = val.ToString(CultureInfo.InvariantCulture);
                }
    
                this.isPaste = true;
            }
    
            /// <summary>
            /// The numberic text box preview text input.
            /// </summary>
            /// <param name="sender"> The sender.</param>
            /// <param name="e"> The e.</param>
            private void NumbericTextBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
            {
                // 如果是粘贴不会引发该事件
                this.isPaste = false;
    
                short val;
    
                // 输入非数字
                if (!short.TryParse(e.Text, out val))
                {
                    // 小于0时,可输入负号
                    if ((this.MinValue < 0) && (e.Text == "-"))
                    {
                        int minusPos = this.Text.IndexOf('-');
    
                        // 未输入负号且负号在第一位
                        if ((minusPos == -1) && (0 == this.SelectionStart))
                        {
                            return;
                        }
                    }
    
                    // 精度大于0时,可输入小数点
                    if ((this.Precision > 0) && (e.Text == "."))
                    {
                        // 解决UpdateSourceTrigger为PropertyChanged时输入小数点文本与界面不一致的问题
                        if (this.SelectionStart > this.Text.Length)
                        {
                            e.Handled = true;
                            return;
                        }
    
                        // 小数点位置
                        int dotPos = this.Text.IndexOf('.');
    
                        // 未存在小数点可输入
                        if (dotPos == -1)
                        {
                            return;
                        }
    
                        // 已存在小数点但处于选中状态,也可输入小数点
                        if ((this.SelectionStart >= dotPos) && (this.SelectionLength > 0))
                        {
                            return;
                        }
                    }
    
                    e.Handled = true;
                }
                else
                {
                    int dotPos = this.Text.IndexOf('.');
                    int cursorIndex = this.SelectionStart;
    
                    // 已经存在小数点,且小数点在光标后
                    if ((dotPos != -1) && (dotPos < cursorIndex))
                    {
                        // 不允许输入超过精度的数
                        if (((this.Text.Length - dotPos) > this.Precision) && (this.SelectionLength == 0))
                        {
                            e.Handled = true;
                        }
                    }
                }
            }
    
            /// <summary>
            /// The numberic text box text changed.
            /// </summary>
            /// <param name="sender"> The sender.</param>
            /// <param name="e"> The e.</param>
            private void NumbericTextBoxTextChanged(object sender, TextChangedEventArgs e)
            {
                if (this.lastLegalText == this.Text)
                {
                    return;
                }
    
                this.OnPreviewTextChanged(e);
    
                // 允许为空
                if (string.IsNullOrEmpty(this.Text))
                {
                    return;
                }
    
                // 粘贴而来的文本
                if (this.isPaste)
                {
                    this.HandlePaste();
                    this.lastLegalText = this.Text;
    
                    return;
                }
    
                double val;
                if (double.TryParse(this.Text, out val))
                {
                    // 保存光标位置
                    int selectIndex = this.SelectionStart;
                    if ((val > this.MaxValue) || (val < this.MinValue))
                    {
                        this.Text = this.lastLegalText;
                        this.SelectionStart = selectIndex;
                        return;
                    }
    
                    this.lastLegalText = this.Text;
                }
    
                this.isPaste = true;
            }
    
            /// <summary>
            /// The numberic text box_ preview key down.
            /// </summary>
            /// <param name="sender"> The sender.</param>
            /// <param name="e"> The e.</param>
            private void NumbericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
            {
                // 过滤空格
                if (e.Key == Key.Space)
                {
                    e.Handled = true;
                }
            }
    
            /// <summary>
            /// The numberic text box_ lost focus.
            /// </summary>
            /// <param name="sender"> The sender.</param>
            /// <param name="e"> The e.</param>
            private void NumbericTextBoxLostFocus(object sender, RoutedEventArgs e)
            {
                if (string.IsNullOrEmpty(this.Text))
                {
                    this.Text = this.lastLegalText;
                }
            }
    
            #endregion Events Handling
        }
    }
    

    IP地址输入框

    IP地址输入框使用了上面的数字输入框,按点时可跳转到IP地址下一部分输入,支持IP地址的粘贴。代码较简单,且有注释,不再多说。

    XAML

    <UserControl x:Class="YiYan127.WPF.Controls.IpAddressControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:controls="clr-namespace:YiYan127.WPF.Controls">
        <UniformGrid Columns="4" TextBoxBase.GotFocus="TextBox_OnGotFocus">
            <DockPanel Margin="5,2">
                <TextBlock VerticalAlignment="Center" DockPanel.Dock="Right" Text="." />
                <controls:NumbericTextBox x:Name="IPPart1" MaxValue="255" MinValue="0"
                                          Precision="0" />
            </DockPanel>
            <DockPanel Margin="0,2,5,2">
                <TextBlock VerticalAlignment="Center" DockPanel.Dock="Right" Text="." />
                <controls:NumbericTextBox x:Name="IPPart2" MaxValue="255" MinValue="0"
                                          Precision="0" />
            </DockPanel>
            <DockPanel Margin="0,2,5,2">
                <TextBlock VerticalAlignment="Center" DockPanel.Dock="Right" Text="." />
                <controls:NumbericTextBox x:Name="IPPart3" MaxValue="255" MinValue="0"
                                          Precision="0" />
            </DockPanel>
            <controls:NumbericTextBox x:Name="IPPart4" Margin="0,2,5,2" MaxValue="255"
                                      MinValue="0" Precision="0" />
        </UniformGrid>
    </UserControl>
    

    后台代码

    namespace YiYan127.WPF.Controls
    {
        using System;
        using System.Collections.Generic;
        using System.Diagnostics.Contracts;
        using System.Text.RegularExpressions;
        using System.Windows;
        using System.Windows.Controls;
        using System.Windows.Input;
    
        /// <summary>
        /// IP地址输入框
        /// </summary>
        public partial class IpAddressControl
        {
            #region Fields
    
            /// <summary>
            /// IP地址的依赖属性
            /// </summary>
            public static readonly DependencyProperty IPProperty = DependencyProperty.Register(
                    "IP",
                    typeof(string),
                    typeof(IpAddressControl),
                    new FrameworkPropertyMetadata(DefaultIP, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IPChangedCallback));
    
            /// <summary>
            /// IP地址的正则表达式
            /// </summary>
            public static readonly Regex IpRegex = new
                Regex(@"^((2[0-4]\d|25[0-5]|(1\d{2})|([1-9]?[0-9]))\.){3}(2[0-4]\d|25[0-4]|(1\d{2})|([1-9][0-9])|([1-9]))$");
    
            /// <summary>
            /// 默认IP地址
            /// </summary>
            private const string DefaultIP = "127.0.0.1";
    
            private static readonly Regex PartIprRegex = new Regex(@"^(\.?(2[0-4]\d|25[0-5]|(1\d{2})|([1-9]?[0-9]))\.?)+$");
    
            /// <summary>
            /// 输入框的集合
            /// </summary>
            private readonly List<NumbericTextBox> numbericTextBoxs = new List<NumbericTextBox>();
    
            /// <summary>
            /// 当前活动的输入框
            /// </summary>
            private NumbericTextBox currentNumbericTextBox;
    
            #endregion Fields
    
            #region Constructors
    
            public IpAddressControl()
            {
                InitializeComponent();
                this.numbericTextBoxs.Add(this.IPPart1);
                this.numbericTextBoxs.Add(this.IPPart2);
                this.numbericTextBoxs.Add(this.IPPart3);
                this.numbericTextBoxs.Add(this.IPPart4);
                this.KeyUp += this.IpAddressControlKeyUp;
    
                this.UpdateParts(this);
    
                foreach (var numbericTextBox in this.numbericTextBoxs)
                {
                    numbericTextBox.PreviewTextChanged += this.NumbericTextBox_OnPreviewTextChanged;
                }
    
                foreach (var numbericTextBox in this.numbericTextBoxs)
                {
                    numbericTextBox.TextChanged += this.TextBoxBase_OnTextChanged;
                }
            }
    
            #endregion Constructors
    
            #region Properties
    
            public string IP
            {
                get
                {
                    return (string)GetValue(IPProperty);
                }
    
                set
                {
                    SetValue(IPProperty, value);
                }
            }
    
            #endregion Properties
    
            #region Private Methods
    
            /// <summary>
            /// IP值改变的响应
            /// </summary>
            /// <param name="dependencyObject"></param>
            /// <param name="dependencyPropertyChangedEventArgs"></param>
            private static void IPChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
            {
                if (dependencyPropertyChangedEventArgs.NewValue == null)
                {
                    throw new Exception("IP can not be null");
                }
    
                var control = dependencyObject as IpAddressControl;
                if (control != null)
                {
                    control.UpdateParts(control);
                }
            }
    
            private void UpdateParts(IpAddressControl control)
            {
                string[] parts = control.IP.Split(new[] { '.' });
                control.IPPart1.Text = parts[0];
                control.IPPart2.Text = parts[1];
                control.IPPart3.Text = parts[2];
                control.IPPart4.Text = parts[3];
            }
    
            #endregion Private Methods
    
            #region Event Handling
    
            /// <summary>
            /// 按键松开的响应
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void IpAddressControlKeyUp(object sender, KeyEventArgs e)
            {
                if (e.Key == Key.OemPeriod || e.Key == Key.Decimal)
                {
                    if (this.currentNumbericTextBox != null)
                    {
                        int index = this.numbericTextBoxs.IndexOf(this.currentNumbericTextBox);
                        int next = (index + 1) % this.numbericTextBoxs.Count;
                        this.numbericTextBoxs[next].Focus();
                        this.numbericTextBoxs[next].SelectionStart = this.numbericTextBoxs[next].Text.Length;
                    }
                }
            }
    
            /// <summary>
            /// 获得焦点的响应
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void TextBox_OnGotFocus(object sender, RoutedEventArgs e)
            {
                this.currentNumbericTextBox = e.OriginalSource as NumbericTextBox;
            }
    
            private void NumbericTextBox_OnPreviewTextChanged(object sender, TextChangedEventArgs e)
            {
                var numbericTextBox = sender as NumbericTextBox;
                Contract.Assert(numbericTextBox != null);
    
                if (PartIprRegex.IsMatch(numbericTextBox.Text))
                {
                    var ips = numbericTextBox.Text.Split('.');
    
                    if (ips.Length == 1)
                    {
                        return;
                    }
    
                    int index = this.numbericTextBoxs.IndexOf(numbericTextBox);
                    int pointer2Ips = 0;
                    for (int i = index; i < this.numbericTextBoxs.Count; i++)
                    {
                        while (pointer2Ips < ips.Length && string.IsNullOrEmpty(ips[pointer2Ips]))
                        {
                            pointer2Ips++;
                        }
    
                        if (pointer2Ips >= ips.Length)
                        {
                            return;
                        }
    
                        this.numbericTextBoxs[i].Text = ips[pointer2Ips];
                        pointer2Ips++;
                    }
                }
            }
    
            private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e)
            {
                var ip = string.Format(
                    "{0}.{1}.{2}.{3}",
                    this.IPPart1.Text,
                    this.IPPart2.Text,
                    this.IPPart3.Text,
                    this.IPPart4.Text);
                if (IpRegex.IsMatch(ip))
                {
                    this.IP = ip;
                }
            }
    
            #endregion     Event Handling
        }
    }
    posted on 2019-01-04 01:00 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

    转载于:https://www.cnblogs.com/lonelyxmas/p/10217756.html

    展开全文
  • WPF数字输入框设计

    2021-08-07 16:45:43
    数字输入框基于TextBox。 2.1 仅能输入数字和小数点 处理键盘按下事件 TextBox txt = sender asTextBox; //屏蔽非法按键 if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key....

    1  功能要求

    1. 仅能输入数字和小数点。
    2. 禁用复制、剪切、粘贴。
    3. 禁用输入法。

    2  功能设计

    数字输入框基于TextBox。

    2.1  仅能输入数字和小数点

    处理键盘按下事件

        TextBox txt = sender as TextBox;

        //屏蔽非法按键

        if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)

        {

            if (txt.Text.Contains(".") && e.Key == Key.Decimal)

            {

                e.Handled = true;

                return;

            }

            e.Handled = false;

        }

        else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) &&

                 e.KeyboardDevice.Modifiers != ModifierKeys.Shift)

        {

            if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)

            {

                e.Handled = true;

                return;

            }

            e.Handled = false;

        }

        else

        {

            e.Handled = true;

        }

    2.2  禁用复制、剪切、粘贴功能

    (1)添加命令绑定

    <TextBox.CommandBindings>

    <CommandBinding Command="ApplicationCommands.Paste" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>

    <CommandBinding Command="ApplicationCommands.Cut" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>

    <CommandBinding Command="ApplicationCommands.Copy" CanExecute="NumericBox_CommandBinding_CanExecute"></CommandBinding>

    </TextBox.CommandBindings>

    添加绑定处理函数NumericBox_CommandBinding_CanExecute

    /// <summary>

    /// 禁止文本框使用复制、粘贴、剪切功能

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    private void NumericBox_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)

    {

        e.CanExecute = false;

        e.Handled = true;

    }

    1. 禁用鼠标右键快捷菜单

    TextBox添加属性:

    ContextMenu="{x:Null}"

    2.3  禁用输入法

    TextBox添加属性:

    InputMethod.IsInputMethodEnabled="False"

    3  备注

    可以通过修改限制字符,将控件更改为其他类型输入框。

    展开全文
  • 之前遇到的一个问题就是,passwordbox 输入框在系统自带输入法处于中文输入状态时不能输入数字,一定要切换到英文输入状态时才能输入数字,后来找了很多办法发现都没有很有效的解决办法,最后经过N次实验,一行代码...

    之前遇到的一个问题就是,passwordbox 输入框在系统自带输入法处于中文输入状态时不能输入数字,一定要切换到英文输入状态时才能输入数字,后来找了很多办法发现都没有很有效的解决办法,最后经过N次实验,一行代码解决问题,不用什么强制转换为英文输入法等,只需将当前输入法挂起即可。

    InputMethod.IsInputMethodSuspended="True"

    展开全文
  • 要求:只能输入数字和小数点,可以设置最大值,最小值,小数点前长度,小数点后长度(支持绑定设置); 代码如下: 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using ...
  • WPF和Expression Blend开发实例:一个样式实现的数字输入框 原文:WPF和Expression Blend开发实例:一个样式实现的数字输入框今天来一个比较奇淫技巧的手法,很少人用,同时也不推荐太过频繁的使用. 先上...
  • VS2013下WPF实现数字键盘,点击界面上的输入框,能够自动弹出数字键盘,显示3x4 布局的软键盘,有半透明效果
  • } } return new ValidationResult(false, "请输入 0 至 100的数字"); } } 前端XAML代码调用上面的类,并自定义错误提示模板 ...
  • WPF数字键盘

    2021-06-11 13:59:12
    开发一个无状态的app,仿小键盘输入,可以在记事本等能够又输入光标的应用获取输入的内容。
  • 如果输入框中有数字,则全选数字。 3、Delete就正常从后面删除;Enter暂时无操作();Tab自动跳转焦点; 4、Back往前删除,如果当前输入框为空,则跳转到前面一个输入框;如果前面一个输入框数字,则删除一位数字...
  • WPF使用ValidationRule验证控件内容 写一个或多个实现ValidationRule接口的类 /// <summary> /// 不能为空验证 /// </summary> public class NotNullValidationRule : ValidationRule { public ...
  • WPF 输入数字和小数点的文本框,支持输入0-9的数字,小数点和删除键,其他的键都被禁止输入
  • 以前需要做一个数字输入的InputBox,结果无奈需求太BT,搞得焦头烂额,重做了无数次。无奈之下,再次Google,发现早有成熟的插件了(闷在家里造轮子果然不好啊),autoNumeric使用方便,功能强大,现在介绍给大家,一个...
  • WPF自定义数字文本框控件

    千次阅读 2018-09-17 10:53:59
    参考:https://www.cnblogs.com/yiyan127/p/WPF-NumbericTextBox.html#_label1
  • WPF实现, BindConvert, Comboximage GridSplit MessageBox ScrollViewer TabControlTest 倒计时 数字加减文本框 WPF圆形图像
  • wpf 限制textbox只能输入数字及特殊键

    千次阅读 2019-12-24 13:31:25
    使用vs2015进行wpf设计时,发现限制输入数字时,Keydown事件无法检测到空格的输入,后经过查资料调试,发现PreviewKeyDown可以满足检测输入所有值合法性的要求,我的textbox输入框中只允许输入(大小键盘中)的数字0-...
  • WPF 只允许输入数字的文本框

    千次阅读 2014-12-16 16:46:09
    在网上有不少关入这方面的资料,下面是我选用的一个方案 public NumberTextBox()  {  InitializeComponent();  this.KeyDown += NumberTextBox_KeyDown;... this.TextChanged += NumberTextBox_Tex
  • <TextBox x:Name="txt_SewagePrice" Grid.Row="3" Grid.Column="1" VerticalContentAlignment="Center" PreviewTextInput="txt_PreviewTextInput" ...
  • /// &lt;summary&gt; /// 文本框文本输入事件 /// &lt;/summary&gt; private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex regex = ...
  • WPF 文本框只能输入数字

    千次阅读 2018-03-12 16:12:07
    只需要两步:1.禁掉输入法:&lt;Window x:Class="WpfModelViewApplication1.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="...
  • 在做其他平台,无论是WinForm、WPF、Silverlight还是Asp.Net,大家可能都会遇到这样的需求:输入框只能输入数字。其实实现方式都大同小异,获取输入文字的key,判断其是否是可以输入的范围。下面讲一下,如何在...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 400
精华内容 160
关键字:

wpf数字输入框