功能更新
This commit is contained in:
43
Melskin/Converters/PercentageConverter.cs
Normal file
43
Melskin/Converters/PercentageConverter.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user