using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Elwig.Controls { public class UnitConverter : DependencyObject, IValueConverter { public static readonly DependencyProperty UnitProperty = DependencyProperty.Register(nameof(Unit), typeof(string), typeof(UnitConverter), new FrameworkPropertyMetadata(null)); public string Unit { get => (string)GetValue(UnitProperty); set => SetValue(UnitProperty, value); } public static readonly DependencyProperty PrecisionProperty = DependencyProperty.Register(nameof(Precision), typeof(byte), typeof(UnitConverter), new FrameworkPropertyMetadata((byte)0)); public byte Precision { get => (byte)GetValue(PrecisionProperty); set => SetValue(PrecisionProperty, value); } public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return null; } var fmt = $"{{0:N{Precision}}}"; var unit = $"{(Unit != null ? " " : "")}{Unit}"; if (value is int i) { return $"{string.Format(fmt, i)}{unit}"; } else if (value is decimal d) { return $"{string.Format(fmt, d)}{unit}"; } return Binding.DoNothing; } public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }