我正在尝试使用两个阈值转换一个值,对数据库的调用将返回三个变量
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";
}
最佳答案
这当然是一种方法,特别是如果每次使用绑定(bind)时范围都会改变,但是,如果您要一遍又一遍地重复使用相同的值,您可以声明属性值转换器并在初始化时设置它们。
public int upperThreshold { get; set; }
public int lowerThreshold { get; set; }
public string lowImage { get; set; }
public string middleImage { get; set; }
public string highImage { get; set; }
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
{
if ((double)value < lowerThreshold)
{
//red
return lowImage;
}
else if ((double)value > upperThreshold)
{
//green
return highImage;
}
else
{
//amber
return middleImage;
}
}
return "Error";
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return "Not Possible";
}
}
<local:RangeToImageConverter
x:Name="MyRangeConverter"
upperThreshold="30"
lowerThreshold="50"
lowImage="/red32.png"
middleImage="/amber32.png"
highImage="/green32.png"
/>
关于c# - Silverlight 使用阈值转换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6495288/