我正在尝试使用两个阈值转换一个值,对数据库的调用将返回三个变量
Double Score;
Double LowerThreshold;
Double HigherThreshold;
如果分数低于下限阈值,则显示红色图像,如果在两个阈值之间,则显示琥珀色,如果高于上限阈值,则显示绿色。
目前我正在使用自定义 ValueConverter 但我不确定这是否是最好的方法。我将高阈值和低阈值合并在一起,使它们看起来像“30,50”,然后解析字符串中的值并计算出要显示的图像。
这是我用于 ValueConverter 的代码
public class ScoreConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
{
if (parameter is string)
{
if ((parameter as string).Contains(","))
{
string[] thresholds = (parameter as string).Split(',');
int lowerThreshold;
int upperThreshold;
bool success;
success = int.TryParse(thresholds[0], out lowerThreshold);
if (!success)
return "Error";
success = int.TryParse(thresholds[1], out upperThreshold);
if (!success)
return "Error";
if ((double)value < lowerThreshold)
{
//red
return "/Red32.png";
}
else if ((double)value > upperThreshold)
{
//green
return "/Green32.png";
}
else
{
//amber
return "/Amber32.png";
}
}
}
}
return "Error";
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return "Not Possible";
}
}
任何关于更好方法的建议将不胜感激,
谢谢
编辑
决定使用如下代码,服务端返回如下结构
public class ScoreInformation
{
public double Score { get; set; }
public double lowerThreshold { get; set; }
public double upperThreshold { get; set; }
}
这是转换它并显示正确图像的代码
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is ScoreInformation)
{
ScoreInformation si = (ScoreInformation)value;
if (si.Score < si.lowerThreshold)
{
return "Red32.png";
}
else if (si.Score > si.upperThreshold)
{
//green
return "Green32.png";
}
else
{
//amber
return "Orange32.png";
}
}
return "Grey32.png";
}