Files
Shrlalgo.RvKits/Melskin/Converters/PercentageConverter.cs
2026-02-17 22:17:13 +08:00

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