2025-08-20 12:10:13 +08:00
|
|
|
|
using System.Globalization;
|
2025-08-12 23:08:54 +08:00
|
|
|
|
using System.Windows.Data;
|
|
|
|
|
|
|
2026-01-02 17:30:41 +08:00
|
|
|
|
namespace Melskin.Converters;
|
2025-08-12 23:08:54 +08:00
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 将0.0-1.0范围的浮点数值转换为0%-100%百分比字符串的转换器。
|
|
|
|
|
|
/// 此转换器用于将饱和度和亮度值显示为百分比格式,提供更直观的用户界面。
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class PercentageConverter : IValueConverter
|
|
|
|
|
|
{
|
2025-08-24 13:49:55 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 单例实例,用于访问已创建的PercentageConverter对象。
|
|
|
|
|
|
/// 通过使用此静态只读属性,可以在不重复创建转换器实例的情况下,在应用程序中的任何地方方便地引用和使用该转换器。
|
|
|
|
|
|
/// </summary>
|
2025-08-20 12:10:35 +08:00
|
|
|
|
public static readonly PercentageConverter Instance = new();
|
2025-08-20 12:10:13 +08:00
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
|
public object Convert(object? value, System.Type targetType, object? parameter, CultureInfo culture)
|
2025-08-12 23:08:54 +08:00
|
|
|
|
{
|
|
|
|
|
|
if (value is double doubleValue)
|
|
|
|
|
|
{
|
|
|
|
|
|
// 将 0.0-1.0 的值转换为 0-100 的百分比字符串
|
|
|
|
|
|
return $"{Math.Round(doubleValue * 100.0)}%";
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return "0%";
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-20 12:10:13 +08:00
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
|
public object ConvertBack(object? value, System.Type targetType, object? parameter, CultureInfo culture)
|
2025-08-12 23:08:54 +08:00
|
|
|
|
{
|
2025-08-20 12:10:13 +08:00
|
|
|
|
if (value is not string percentStr) return DependencyProperty.UnsetValue;
|
|
|
|
|
|
// 移除 '%' 符号并尝试解析
|
|
|
|
|
|
if (double.TryParse(percentStr.TrimEnd('%'), out var percent))
|
2025-08-12 23:08:54 +08:00
|
|
|
|
{
|
2025-08-20 12:10:13 +08:00
|
|
|
|
var clampedPercent = Math.Max(0, Math.Min(100, percent));
|
|
|
|
|
|
return clampedPercent / 100.0; // 转换回 0.0-1.0 范围
|
2025-08-12 23:08:54 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 如果转换失败,返回 UnsetValue 以保留原值
|
|
|
|
|
|
return DependencyProperty.UnsetValue;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|