Different color for different items in ListView

2019-06-02 08:43发布

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?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-02 09:31

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

查看更多
beautiful°
3楼-- · 2019-06-02 09:35

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>
查看更多
登录 后发表回答