C00225155-02/C00225155/MegaRobo.C00225155/MegaRobo.C00225155App/Converters/DivisionConverter.cs

93 lines
3.1 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace MegaRobo.C00225155App.Converters
{
public class DivisionConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// 确保有两个值传入
if (values == null || values.Length < 2)
return 0.0;
// 尝试解析分子和分母
double numerator = TryParseDouble(values[0]);
double denominator = TryParseDouble(values[1]);
// 处理分母为零的情况
if (denominator == 0)
return 0.0;
// 计算比例并确保在 [0,1] 范围内
double ratio = numerator / denominator;
return Math.Max(0, Math.Min(1, ratio));
}
private double TryParseDouble(object value)
{
if (value is double d) return d;
if (value is int i) return i;
if (value is float f) return f;
if (value is decimal dec) return (double)dec;
return 0.0;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
public class InverseDivisionConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// 确保有两个值传入
if (values == null || values.Length < 2 || values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue)
return 0.0;
// 尝试解析分子和分母
double numerator = TryParseDouble(values[0]);
double denominator = TryParseDouble(values[1]);
// 处理分母为零的情况
if (denominator == 0)
return 1.0; // 分母为零时返回1表示100%已使用)
// 计算剩余比例
double remainingRatio = numerator / denominator;
// 计算已使用比例1 - 剩余比例
double usedRatio = 1.0 - remainingRatio;
Console.WriteLine($"InverseDivisionConverter: numerator={numerator}, denominator={denominator}, remainingRatio={remainingRatio}, usedRatio={usedRatio}");
// 确保在 [0,1] 范围内
return Math.Max(0, Math.Min(1, usedRatio));
}
private double TryParseDouble(object value)
{
if (value is double d) return d;
if (value is int i) return i;
if (value is float f) return f;
if (value is decimal dec) return (double)dec;
return 0.0;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}