不同的颜色在不同的ListView项目 [英] Different color for different items in ListView

查看:83
本文介绍了不同的颜色在不同的ListView项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能自动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; }
}

这是一个XALM:

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>

我怎样才能让苹果与所有行是红色,黄色橘子e.t.c.没有编辑水果类?

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

推荐答案

申报View.xaml资源下面的样式,它将被应用到每个ListView项。考虑到每个ListViewItem.DataContext设置键入水果你钙处理对名称属性设置DataTrigger的对象:

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>

这篇关于不同的颜色在不同的ListView项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆