BDU/ATS/Converters/HexConverter.cs

39 lines
1.1 KiB
C#
Raw 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.Threading.Tasks;
using System.Windows.Data;
namespace ATS.Converters
{
public class HexConverter : IValueConverter
{
// 显示时int → hex 字符串
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is int i)
return $"0x{i:X}"; // 例如 255 → 0xFF
return "0x0";
}
// 用户输入时hex 字符串 → int
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var str = value?.ToString()?.Trim();
if (string.IsNullOrWhiteSpace(str))
return 0;
if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
str = str.Substring(2);
if (int.TryParse(str, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int result))
return result;
return 0; // 或 return DependencyProperty.UnsetValue;
}
}
}