106 lines
3.2 KiB
C#
106 lines
3.2 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Windows.Data;
|
|
|
|
namespace CtrEditor.Converters
|
|
{
|
|
/// <summary>
|
|
/// Converter para calcular la altura del nivel de líquido en un tanque
|
|
/// basado en el porcentaje de llenado y el tamaño del tanque
|
|
/// </summary>
|
|
public class TankLevelToHeightConverter : IMultiValueConverter
|
|
{
|
|
public TankLevelToHeightConverter()
|
|
{
|
|
// Constructor sin logging para evitar bloqueos
|
|
}
|
|
|
|
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
|
|
{
|
|
if (values.Length != 2)
|
|
{
|
|
return 0.0;
|
|
}
|
|
|
|
// Convertir flexiblemente los valores a double
|
|
if (!TryConvertToDouble(values[0], out double fillPercentage) ||
|
|
!TryConvertToDouble(values[1], out double tankSize))
|
|
{
|
|
return 0.0;
|
|
}
|
|
|
|
try
|
|
{
|
|
// Calcular altura basada en el porcentaje de llenado
|
|
// tankSize está en metros, convertir a píxeles (aproximación: 100 píxeles por metro)
|
|
var tankHeightPixels = tankSize * 100.0;
|
|
|
|
// Altura del líquido = porcentaje de llenado * altura total del tanque
|
|
var liquidHeight = (fillPercentage / 100.0) * tankHeightPixels;
|
|
|
|
// Aplicar margen interno (restar 8 píxeles para los márgenes del XAML)
|
|
var availableHeight = tankHeightPixels - 8.0; // 4px arriba + 4px abajo
|
|
var adjustedHeight = (fillPercentage / 100.0) * availableHeight;
|
|
|
|
// Asegurar que la altura sea positiva y no exceda el contenedor
|
|
var result = Math.Max(0.0, Math.Min(adjustedHeight, availableHeight));
|
|
return result;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// En caso de error, retornar 0
|
|
return 0.0;
|
|
}
|
|
}
|
|
|
|
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
|
|
{
|
|
throw new NotImplementedException("TankLevelToHeightConverter no soporta conversión inversa");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Convierte un valor a double de manera flexible
|
|
/// </summary>
|
|
private static bool TryConvertToDouble(object value, out double result)
|
|
{
|
|
result = 0.0;
|
|
|
|
if (value == null)
|
|
return false;
|
|
|
|
if (value is double d)
|
|
{
|
|
result = d;
|
|
return true;
|
|
}
|
|
|
|
if (value is float f)
|
|
{
|
|
result = f;
|
|
return true;
|
|
}
|
|
|
|
if (value is int i)
|
|
{
|
|
result = i;
|
|
return true;
|
|
}
|
|
|
|
if (value is decimal dec)
|
|
{
|
|
result = (double)dec;
|
|
return true;
|
|
}
|
|
|
|
// Intentar conversión de string
|
|
if (value is string str && double.TryParse(str, out result))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
}
|