Files
SZMCToolkit.RevitAddins/WpfAppTest/UnitConverter.cs
2026-02-23 10:28:26 +08:00

57 lines
1.8 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
}
}
}