shtkuh
shtkuh

Reputation: 459

Different color for different items in ListView

How can I define different colors in each row of ListView automatically? for example if I have such classes:

public partial class MainWindow : Window
{
    private ObservableCollection<Fruit> _fruits = new ObservableCollection<Fruit>();
    public ObservableCollection<Fruit> Fruits { get { return _fruits; } }
    public MainWindow()
    {
        Fruits.Add(new Fruit { Name = "apple", Count = 3 });
        Fruits.Add(new Fruit { Name = "orange", Count = 10 });
        Fruits.Add(new Fruit { Name = "apple", Count = 3 });
        Fruits.Add(new Fruit { Name = "banana", Count = 8 });

        InitializeComponent();
    }
}

public class Fruit
{
    public string Name { get; set; }
    public int Count { get; set; }
}

And this is a XALM:

<Grid>
    <ListView Name="listView1" ItemsSource="{Binding Fruits}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Fruit" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Count" DisplayMemberBinding="{Binding Count}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

How can I make all rows with apples to be red, oranges yellow e.t.c. without edit Fruit class?

Upvotes: 1

Views: 3115

Answers (2)

madcyree
madcyree

Reputation: 1457

There are several ways to do that.

The first way is to use DataTemplates which allows you to select color by state of your object. You can read about them here

Also, you can always specify alternation count of rows. You can read about it here

Upvotes: 1

sll
sll

Reputation: 62504

Declare following Style in View.xaml resources, it will be applied to the each ListView Item. Considering that into the each ListViewItem.DataContext is set object of type Fruit you ca set DataTrigger on Name property:

<Style TargetType="ListViewItem"> 
    <Style.Triggers>
         <DataTrigger Binding="{Binding Name}" Value="apple">
               <Setter Property="Background" Value="Green" />
         </DataTrigger>
         <DataTrigger Binding="{Binding Name}" Value="orange">
               <Setter Property="Background" Value="orange" />
         </DataTrigger>
    </Style.Triggers>
</Style>

Upvotes: 2

Related Questions