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?
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
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 onName
property: