• wpf 附加属性样例代码


    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Text.RegularExpressions;

    namespace zl_screensaver
    {
        public static class TextBoxExtensions
        {
            public static readonly DependencyProperty IsNumericProperty =
                DependencyProperty.RegisterAttached("IsNumeric", typeof(bool), typeof(TextBoxExtensions),
                    new PropertyMetadata(false, OnIsNumericChanged));

            public static bool GetIsNumeric(DependencyObject obj)
            {
                return (bool)obj.GetValue(IsNumericProperty);
            }

            public static void SetIsNumeric(DependencyObject obj, bool value)
            {
                obj.SetValue(IsNumericProperty, value);
            }

            private static void OnIsNumericChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                TextBox textBox = d as TextBox;
                if (textBox == null) return;

                if ((bool)e.NewValue)
                {
                    textBox.PreviewTextInput += TextBox_PreviewTextInput;
                    DataObject.AddPastingHandler(textBox, OnPaste);
                    InputMethod.SetIsInputMethodEnabled(textBox, false); // 禁用输入法
                }
                else
                {
                    textBox.PreviewTextInput -= TextBox_PreviewTextInput;
                    DataObject.RemovePastingHandler(textBox, OnPaste);
                    InputMethod.SetIsInputMethodEnabled(textBox, true); // 启用输入法
                }
            }

            private static void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
            {
                if (!IsTextNumeric(e.Text))
                {
                    e.Handled = true;
                }
            }

            private static void OnPaste(object sender, DataObjectPastingEventArgs e)
            {
                if (e.DataObject.GetDataPresent(typeof(string)))
                {
                    string text = (string)e.DataObject.GetData(typeof(string));
                    if (!IsTextNumeric(text))
                    {
                        e.CancelCommand();
                    }
                }
                else
                {
                    e.CancelCommand();
                }
            }

            private static bool IsTextNumeric(string text)
            {
                Regex regex = new Regex("[^0-9]+"); // 只允许数字
                return !regex.IsMatch(text);
            }
        }
    }
     

  • 相关阅读:
    用Html标签和CSS3写的一个手机
    【高级IO】第一讲(5种IO模型的介绍、select函数介绍、一个简单select服务器)
    软件运维面试题
    Server Response!internal server error
    2023年11月架构设计师上午真题及答案
    网络基础-ICMP协议
    golang 多个struct 转换融合为一个json,平级融合或者多级融合
    宝塔面板网站解决跨域问题
    三十七、【进阶】SQL的explain
    Vue项目实战之人力资源平台系统(三)主页模块
  • 原文地址:https://blog.csdn.net/zhang8593/article/details/139438168