using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace WpfAppTest { internal class UnitConverter : IValueConverter { private string DefaultUnit { get; set; } = "mm"; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; if (value is double d) { string unit = parameter as string ?? DefaultUnit; // 使用StringFormat时,value会先被格式化,这里直接拼接单位 return $"{d.ToString(culture)} {unit}"; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string str) { // 提取纯数字字符串(允许中间态如 '1.', '-.') str = str.Trim(); var match = Regex.Match(str, @"[-+]?[0-9]*\.?[0-9]*"); if (match.Success) { string numberPart = match.Value; // 处理中间态输入,允许返回未完成的文本(让 UI 不抖动) if (string.IsNullOrEmpty(numberPart) || numberPart.EndsWith("-") || numberPart.EndsWith(".") || numberPart.EndsWith("-.")) return DependencyProperty.UnsetValue; if (double.TryParse(numberPart, NumberStyles.Any, culture, out double result)) return result; } } return DependencyProperty.UnsetValue; } } }