如何更改列表视图中最高 3 项的前景色。由 C# WPF

How to change the Foreground color of highest 3 items in a listview. c# WPF

我正在寻找更改列表视图中 前 3 标签的前景色的方法。我的工作代码取决于使用 ObservableCollection 的值,但正在寻找仅更改前 3 个标签颜色的方法。

我的 ProductItem(主题)中的代码

<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();
        }
    }

您可以使用托管标签的 ListViewItem 的索引号。比方说,您想将前 3 项的前景更改为橙色,请修改 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();
    }
}

然后修改Foreground的绑定属性.

<Label Content="{Binding Tonnes}">
    <Label.Foreground>
        <MultiBinding Converter="{StaticResource ColorConverter}">
            <Binding Path="Tonnes"/>
            <Binding RelativeSource="{RelativeSource AncestorType={x:Type ListViewItem}}"/>
        </MultiBinding>
    </Label.Foreground>
</Label>