简体   繁体   中英

How to color each item in listView control in wpf in a different color?

First i tried this, but not sure where and how to implement it.

<ListView.Resources>                
    <ControlTemplate x:Key="SelectedTemplate" TargetType="ListViewItem">
        <Border CornerRadius="5" BorderThickness="1" BorderBrush="DarkGray" Background="#FF92C6F9" Padding="2" HorizontalAlignment="Left" Margin="5" Tag="{Binding Value}" Cursor="Hand" MouseUp="Border_MouseUp_1">                        
            <TextBlock Text="{Binding Name}" Margin="5" />
        </Border>
    </ControlTemplate>
    <Style TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <Border CornerRadius="5" BorderThickness="1" BorderBrush="DarkGray" Background="WhiteSmoke" Padding="2" HorizontalAlignment="Left" Margin="5" Tag="{Binding Value}" Cursor="Hand" MouseUp="Border_MouseUp_1" >                                    
                        <TextBlock Text="{Binding Name}" Margin="5" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsSelected" Value="true" />
                    <Condition Property="Selector.IsSelectionActive" Value="true" />
                </MultiTrigger.Conditions>                            
                <Setter Property="Template" Value="{StaticResource SelectedTemplate}" />                            
            </MultiTrigger>
        </Style.Triggers>
    </Style>
</ListView.Resources>

i tried after the listview name or inside the grid part but got too many errors.

this is my xaml code

<Window x:Class="Lab_ListView.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Lab_ListView"
        mc:Ignorable="d"
        Title="Video Game List" Height="450" Width="800">
    <Grid Margin="0,0,10,10">
        <Label Content="Game Name" HorizontalAlignment="Left" Margin="40,59,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="GameNameTextBox" HorizontalAlignment="Left" Height="23" Margin="121,62,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="366"/>
        <Button x:Name="AddBtn" Content="Add" HorizontalAlignment="Left" Margin="121,151,0,0" VerticalAlignment="Top" Width="75" Click="AddBtn_Click"/>
        <ListView x:Name="VideoGameListView" HorizontalAlignment="Left" Height="166" Margin="40,203,0,0" VerticalAlignment="Top" Width="447">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Game Name" DisplayMemberBinding="{Binding GameName}"/>
                    <GridViewColumn Header="Rating" DisplayMemberBinding="{Binding Rating}"/>
                    <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Label Content="Rating" HorizontalAlignment="Left" Margin="40,90,0,0" VerticalAlignment="Top"/>
        <Label Content="Price" HorizontalAlignment="Left" Margin="40,121,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="PriceTextBox" HorizontalAlignment="Left" Height="23" Margin="121,123,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="366"/>
        <TextBox x:Name="RatingTextBox" HorizontalAlignment="Left" Height="23" Margin="121,92,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="366"/>

    </Grid>
</Window>

this is the code of the class Cropped_Info

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lab_ListView
{
    class Cropped_Info
    {
        private string m_GameName;
        private string m_Rating;
        private double m_Price;

        public string GameName
        {
            get
            {
                return m_GameName;
            }

            set
            {
                m_GameName = value;

            }
        }

        public string Rating
        {
            get
            {
                return m_Rating;
            }

            set
            {
                m_Rating = value;

            }
        }

        public double Price
        {
            get
            {
                return m_Price;
            }

            set
            {
                m_Price = value;

            }
        }

        public Cropped_Info()
        {
            GameName = " ";
            Rating = " ";
            Price = 0.0;
        }

    }
}

and the main xaml.cs code where i'm adding the items to the listView

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Lab_ListView
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Cropped_Info vg = new Cropped_Info();
        int counter = 0;
        Random random;
        List<Cropped_Info> list = new List<Cropped_Info>();
        System.Windows.Threading.DispatcherTimer dispatcherTimer;

        public MainWindow()
        {
            InitializeComponent();

            random= new Random();

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += DispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0);
            dispatcherTimer.Start();
        }

        private void DispatcherTimer_Tick(object sender, EventArgs e)
        {
            vg = new Cropped_Info();
            vg.GameName = randStr(5) + " " + counter.ToString();
            VideoGameListView.Items.Add(vg);

            if(counter == 1000)
            {
                dispatcherTimer.Stop();

                for(int i = 0; i < VideoGameListView.Items.Count; i++)
                {
                    var tt = VideoGameListView.Items[i];
                    
                }
            }

            counter++;
        }

        public string randStr(int len)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
            return new string(Enumerable.Repeat(chars, len).Select(s => s[random.Next(s.Length)]).ToArray());
        }
    }
}

i want that each string item that is added to the listView to be colored in some color can be random color but the main goal is to color each item.

You can use a converter to achieve that. For example, the color's Red channel might depend on the Price. The greater the Price, the more red the color could be, like this:

演示

Here's an example of how that could be done:

MainWindow.xaml

<Window
    x:Class="WpfListViewColorsDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfListViewColorsDemo"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">

    <Window.Resources>
        <local:PriceToBackgroundColorConverter x:Key="PriceToBackgroundColorConverter" />
    </Window.Resources>

    <Grid>
        <ListView x:Name="ListViewItems">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <!--  The Background="{Binding Price, Converter={StaticResource PriceToBackgroundColorConverter}}" is where Price gets converted into a Brush that can be set as the Background  -->
                    <Border
                        Padding="5"
                        Background="{Binding Price, Converter={StaticResource PriceToBackgroundColorConverter}}"
                        BorderThickness="1"
                        CornerRadius="5">
                        <TextBlock Foreground="White">
                            <Run Text="{Binding Name}" />
                            <Run Text="{Binding Price, StringFormat=c}" />
                        </TextBlock>
                    </Border>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

MainWindow.xaml.cs, Item.cs and PriceToBackgroundColorConverter.cs

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfListViewColorsDemo;
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        ListViewItems.ItemsSource = new List<Item>
        {
            new Item()
            {
                Name = "Apple",
                Price = 15.99
            },
            new Item()
            {
                Name = "Peach",
                Price = 24.50
            },
            new Item()
            {
                Name = "Watermelon",
                Price = 39.66
            },
            new Item()
            {
                Name = "Diamond",
                Price = 70.42
            },
            new Item()
            {
                Name = "Unicorn",
                Price = 99.00
            }
        };
    }
}

public class Item
{
    public string? Name { get; set; }
    public double Price { get; set; }
}

public class PriceToBackgroundColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value is double price)
        {
            return ConvertPriceToColor(price);
        }

        return value;
    }

    private Brush ConvertPriceToColor(double price)
    {
        // Add your custom coloring logic here.
        // I'm simply making the color more red as the price goes up (capped at 100).
        var red = Math.Clamp(price, 0, 100) * 255 / 100;
        var color = Color.FromArgb(255, (byte)red, 0, b: 0);
        return new SolidColorBrush(color);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //do nothing here
        return value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM