Files
ShrlAlgoToolkit/Melskin/Converters/Internal/ThumbPositionConverter.cs
2026-02-17 22:17:13 +08:00

48 lines
2.2 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.Internal;
// 根据进度、总宽度和滑块宽度(总高度)直接计算滑块位置
/// <summary>
/// ThumbPositionConverter 类用于根据进度、总宽度和滑块宽度(或总高度)来计算滑块的位置。此转换器实现了 IMultiValueConverter 接口,允许它处理多个输入值,并返回一个基于这些输入值的输出值。
/// 该类提供了一个静态实例 (Instance),可以方便地在 XAML 中重用而无需创建新的实例。
/// </summary>
/// <remarks>
/// 使用时需要传递三个参数进度0.0 到 1.0 之间的数值)、总宽度以及滑块宽度(或当布局为垂直方向时使用总高度)。转换器会根据这些信息计算出滑块应该放置的确切位置。
/// 如果输入值不正确或存在异常情况,则返回 0.0 作为默认位置。
/// </remarks>
internal class ThumbPositionConverter : IMultiValueConverter
{
/// <summary>
/// 获取 ThumbPositionConverter 类的单例实例。
/// 该实例用于根据进度、总宽度和滑块宽度(总高度)直接计算滑块位置。
/// </summary>
/// <remarks>
/// 使用此属性可以方便地在 XAML 或代码中引用 ThumbPositionConverter 的同一实例,从而避免了多次创建对象带来的性能开销。
/// </remarks>
public static ThumbPositionConverter Instance { get; } = new();
/// <inheritdoc />
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length < 3 || values.Any(v => v == null || v == DependencyProperty.UnsetValue))
return 0.0;
try
{
var progress = System.Convert.ToDouble(values[0]);
var totalWidth = System.Convert.ToDouble(values[1]);
var thumbWidth = System.Convert.ToDouble(values[2]);
var maxDistance = totalWidth - thumbWidth;
return progress * Math.Max(0, maxDistance);
}
catch
{
return 0.0;
}
}
/// <inheritdoc />
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException(
);
}