将控件的Foreground 绑定到change_percent 并使用ValueConverter 将其转换为Brush。
这是一个基本的转换器,从红色变为黄色到绿色:
public class PercentToBrushConverter : IValueConverter
{
//http://stackoverflow.com/questions/3722307/is-there-an-easy-way-to-blend-two-system-drawing-color-values/3722337#3722337
private Color Blend(Color color, Color backColor, double amount)
{
byte r = (byte)((color.R * amount) + backColor.R * (1 - amount));
byte g = (byte)((color.G * amount) + backColor.G * (1 - amount));
byte b = (byte)((color.B * amount) + backColor.B * (1 - amount));
return Color.FromRgb(r, g, b);
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//Assumes the percent property to be an int.
int input = (int)value;
Color red = Colors.Red;
Color yellow = Colors.Yellow;
Color green = Colors.Green;
Color color;
if (input <= 50)
{
color = Blend(yellow, red, (double)input/50);
}
else
{
color = Blend(green, yellow, (double)(input - 50) / 50);
}
return new SolidColorBrush(color);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
你可以这样使用:
<ListView>
<ListView.Resources>
<vc:PercentToBrushConverter x:Key="PercentToBrushConverter"/>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Progress">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- An indicator ellipse as suggested by Neil Barnwell -->
<Ellipse Height="16" Width="16" Fill="{Binding change_percent, Converter={StaticResource PercentToBrushConverter}}"/>
<TextBlock Margin="5,0,0,0" Text="{Binding change_percent}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<!-- ... -->
</GridView>
</ListView.View>
</ListView>
如何进行xmlns声明:
您需要在某个命名空间中定义类:
namespace MySolution.ValueConverters
{
public class PercentToBrushConverter : IValueConverter { /*...*/ }
}
这个命名空间可以映射到Window或任何其他父控件中:
<Window ...
xmlns:vc="clr-namespace:MySolution.ValueConverters">
这会将MySolution.ValueConverters 命名空间映射到vc 前缀。更多参考see MSDN。