Different color for different items in ListView

跟風遠走 提交于 2019-12-23 01:52:13

问题


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?


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/8077949/different-color-for-different-items-in-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!