如何自动在ListView的每一行中定义不同的颜色?例如,如果我有这样的类:
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:
<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.没有编辑Fruit类?
答案 0 :(得分:2)
在View.xaml资源中声明以下Style,它将应用于每个ListView项。考虑到每个ListViewItem.DataContext都设置了Fruit
类型的对象,你可以在Name
属性上设置DataTrigger:
<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>
答案 1 :(得分:1)