I'm looking for way to change foreground color for top 3 Lables in my listview. I have working code depends on value using ObservableCollection, but looking for way to change only color for top 3 lables.
Code in my ProductItem(theme)
<Label Content="{Binding Tonnes}"
FontWeight="Bold"
HorizontalAlignment="Center"
Padding="0,0,0,0"
FontSize="16"
Foreground="{Binding Tonnes, Converter={StaticResource ColorConverter}}"/>
ColorCoverter
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
decimal tempValue = decimal.Parse(value.ToString());
string tempString = "Red";
if (tempValue >= 0 && tempValue <= 1)
tempString = "Red";
if (tempValue > 1 && tempValue <= 2)
tempString = "#EDDF00";
if (tempValue > 2 && tempValue <= 5)
tempString = "Green";
SolidColorBrush brush = new SolidColorBrush();
BrushConverter conv = new BrushConverter();
brush = conv.ConvertFromString(tempString) as SolidColorBrush;
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
CodePudding user response:
You can make use of index number of ListViewItem which hosts the Label. Let's say, you want to change Foreground of top 3 items to orange, modify the converter for MultiBinding.
public class ColorConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if ((values is { Length: 2 }) &&
(values[0] is decimal tempValue) &&
(values[1] is ListViewItem listViewItem))
{
ListView listView = (ListView)ItemsControl.ItemsControlFromItemContainer(listViewItem);
int index = listView.ItemContainerGenerator.IndexFromContainer(listViewItem);
if (index <= 2)
return Brushes.Orange; // Brush for top 3 items
// Do the conversion for other items.
}
return DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Then modify the binding of Foreground property.
<Label Content="{Binding Tonnes}">
<Label.Foreground>
<MultiBinding Converter="{StaticResource ColorConverter}">
<Binding Path="Tonnes"/>
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
</MultiBinding>
</Label.Foreground>
</Label>