using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace ATS.Converters { public class HexToDecimalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // 将模型中的十进制值转换为十六进制字符串显示 if (value != null) { if (value.GetType() == typeof(int) && value is int intValue) { return $"0x{intValue:X}"; } } return value!; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { // 将用户输入的十六进制字符串(如 "0x13A")转换回十进制整数 if (value is string stringValue && !string.IsNullOrEmpty(stringValue)) { // 移除可能存在的空格 stringValue = stringValue.Trim(); // 检查是否以 "0x" 或 "0X" 开头 if (stringValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase)&& stringValue.Length>2) { try { // 移除 "0x" 前缀,然后解析为整数 var hexString = stringValue.Substring(2); return System.Convert.ToInt32(hexString, 16); } catch (FormatException) { // 如果格式错误,返回 null 或者抛出异常,取决于您的需求 // 这里我们返回 null,让绑定系统保持原值或触发验证 return Binding.DoNothing; } catch (OverflowException) { return Binding.DoNothing; } } else { // 如果没有 "0x" 前缀,则尝试按十进制解析 try { return System.Convert.ToInt32(stringValue); } catch (FormatException) { return Binding.DoNothing; } catch (OverflowException) { return Binding.DoNothing; } } } return Binding.DoNothing; } } }