Files
elwig/Elwig/Controls/UnitConverter.cs
Lorenz Stechauner f09753ccc2
All checks were successful
Test / Run tests (push) Successful in 2m4s
Remove byte order marks
2024-07-26 19:44:41 +02:00

42 lines
1.5 KiB
C#

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();
}
}
}