当前位置: 首页 > news >正文

wpf 自定义控件,只能输入小数点,并且能控制小数点位数

using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;namespace 项目名称
{public class DoubleTextBox : TextBox{public double? MinValue{get { return (double?)GetValue(MinValueProperty); }set { SetValue(MinValueProperty, value); }}public static readonly DependencyProperty MinValueProperty =DependencyProperty.Register("MinValue", typeof(double?), typeof(DoubleTextBox));public double MaxValue{get { return (double)GetValue(MaxValueProperty); }set { SetValue(MaxValueProperty, value); }}public static readonly DependencyProperty MaxValueProperty =DependencyProperty.Register("MaxValue", typeof(double), typeof(DoubleTextBox), new PropertyMetadata(double.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(DoubleTextBox), 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(DoubleTextBox), new PropertyMetadata(false));public string PreviousText{get { return (string)GetValue(PreviousTextProperty); }set { SetValue(PreviousTextProperty, value); }}public static readonly DependencyProperty PreviousTextProperty =DependencyProperty.Register("PreviousText", typeof(string), typeof(DoubleTextBox), new PropertyMetadata(string.Empty));public int DecimalCount{get { return (int)GetValue(DecimalCountProperty); }set { SetValue(DecimalCountProperty, value); }}public static readonly DependencyProperty DecimalCountProperty =DependencyProperty.Register("DecimalCount", typeof(int), typeof(DoubleTextBox), new PropertyMetadata(3));public string HistoryText{get { return (string)GetValue(HistoryTextProperty); }set { SetValue(HistoryTextProperty, value); }}public static readonly DependencyProperty HistoryTextProperty = DependencyProperty.Register("HistoryText", typeof(string), typeof(DoubleTextBox), new PropertyMetadata(string.Empty));static DoubleTextBox(){DefaultStyleKeyProperty.OverrideMetadata(typeof(DoubleTextBox), new FrameworkPropertyMetadata(typeof(DoubleTextBox)));}public DoubleTextBox(){LostFocus += DoubleTextBox_LostFocus;PreviewTextInput += DoubleTextBox_PreviewTextInput;}private void DoubleTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e){Text = Text.Trim();string txt = Text + e.Text;if (!double.TryParse(txt, out double 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 > MaxValue){Text = MaxValue.ToString(); // 将文本框的值设置为最大值SelectionStart = Text.Length + e.Text.Length;e.Handled = true; // 阻止输入超出取值范围的数字}else if (txt.Contains('.')){var Has = txt.Split('.');if (Has != null && Has.Length > 0 && Has[1] != null){if (Has[1].Length == DecimalCount){double dis = double.Parse(txt);if (MinValue is not null && dis < MinValue && txt.Length >= MinValue.Value.ToString().Length){Text = MinValue.Value.ToString(); // 将文本框的值设置为最小值SelectionStart = Text.Length + e.Text.Length;e.Handled = true; // 阻止输入非数字字符}}else if (Has[1].Length > DecimalCount){Text = string.Format("{0:f" + DecimalCount + "}", value);double dis = double.Parse(txt);if (MinValue is not null && dis < MinValue && txt.Length >= MinValue.Value.ToString().Length){Text = MinValue.Value.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 DoubleTextBox_LostFocus(object sender, RoutedEventArgs e){IsGotFocus = false;Text = Text.Trim();if (string.IsNullOrEmpty(Text)){if (!string.IsNullOrEmpty(HistoryText) && double.TryParse(HistoryText, out double history) && history > MinValue){Text = HistoryText;}else if(!string.IsNullOrEmpty(PreviousText)){Text = PreviousText;}else if (MinValue is not null){Text = MinValue.Value.ToString();}SelectionStart = Text.Length;}else{if (double.TryParse(Text, out double num)){if (num < MinValue){if (!string.IsNullOrEmpty(HistoryText) && double.TryParse(HistoryText, out double history) && history > MinValue){Text = HistoryText;}else{Text = MinValue.ToString();}}else if (num > MaxValue){if (!string.IsNullOrEmpty(HistoryText) && double.TryParse(HistoryText, out double history) && history < MaxValue){Text = HistoryText;}else if (!string.IsNullOrEmpty(PreviousText)){Text = PreviousText;}else{Text = MaxValue.ToString();}}}}}}
}

调用:DecimalCount就是小数点位数,一般不去设置,最多三位小数点。如果失去焦点,当前的数据会时你上次输入的数据,这样不会出现数据为空的情况。

 xmlns:local="clr-namespace:你的项目名"  xmlns:sys="clr-namespace:System;assembly=mscorlib"  <local:DoubleTextBox MinValue="0.001" MaxValue="1000000000" PreviousText="1" Text="{Binding Dilution,TargetNullValue={x:Static sys:String.Empty}}" Width="183" Height="60" MaxLength="10" />

http://www.dtcms.com/a/364367.html

相关文章:

  • 机器学习从入门到精通 - Python环境搭建与Jupyter魔法:机器学习起航必备
  • 如何在modelscope上上传自己的MCP服务
  • 【收藏】2025 前端开发者必备 SVG 资源大全
  • 【2025ICCV-持续学习方向】一种用于提示持续学习(Prompt-based Continual Learning, PCL)的新方法
  • 【CouponHub开发记录】SpringAop和分布式锁进行自定义注解实现防止重复提交
  • RAG|| LangChain || LlamaIndex || RAGflow
  • kafka概念之间关系梳理
  • mac idea 配置了Gitlab的远程地址,但是每次pull 或者push 都要输入密码,怎么办
  • 项目中常用的git命令
  • python基础案例-数据可视化
  • Streamlit 数据看板模板:非前端选手快速搭建 Python 数据可视化交互看板的实用工具
  • 【Linux】为什么死循环卡不死 Linux?3 个核心逻辑看懂进程优先级与 CPU 调度密码
  • Langchain4j 整合MongoDB 实现会话持久化存储详解
  • 电表连网不用跑现场!耐达讯自动化RS485转Profinet网关 远程配置+技术支持,真能做到!
  • 单元测试数据库回滚问题
  • 如何在FastAPI中巧妙隔离依赖项,让单元测试不再头疼?
  • 10 分钟掌握 Selenium 8 大元素定位法:从踩坑到精通
  • Python分布式任务队列:万级节点集群的弹性调度实践
  • 深入剖析Spring Boot中Spring MVC的请求处理流程
  • 电脑接入企业中的网线,为啥网卡上面显示AD域名
  • 智能电视小米电视浏览器兼容性踩坑电视黑屏或者电视白屏,Vue项目从Axios到Fetch的避坑指南
  • 【Pytest】解决Pytest中Teardown钩子的TypeError:实例方法与类方法的调用差异
  • 腾讯Hunyuan-MT-7B翻译模型完全指南:2025年开源AI翻译的新标杆
  • 线性代数第一讲—向量组
  • 强化学习中的模仿学习是什么?
  • HR不会告诉你的秘密:学术简历中,这个内容会被秒标“高光“
  • 亚马逊云代理商:配置安全组规则步骤
  • 日志分析与安全数据上传脚本
  • 迅为RK3568开发板体验OpenHarmony—烧写镜像-安装驱动
  • 技术框架之脚手架实现