uwp:如何根据其值更改列表视图项的背景颜色?
uwp: how to change background color of listview item based on its value?
编辑:UWP 应用与 WPF 应用并非 100% 相同。
我有一个带有 ListView 的 uwp 应用程序。在 ListView 中,我使用带有 class 测试的 DataTemplate。它显示测试的名称和分数。
我想要完成的是一个触发器!?检查点数是否大于即:50,然后将 ListViewItem 的背景颜色更改为红色。
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Tests">
<Grid>
<TextBlock Text="{x:Bind Name}" />
<TextBlock Text="{x:Bind Points}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
您可以使用类似的东西:
在那个例子中,海报只是检查它是偶数还是奇数,以创建交替颜色。
if (index % 2 == 0)
{
...
}
在你的情况下,你可以这样做:
if(item.Points > 50)
{
return this.RedBackgroundStyle;
}
您可以通过多种方式做到这一点:
- 使用
ItemContrainerStyleSelector
: the sample 我找到了
- 使用
DataTemplateSelector
: the sample 我找到了
- 使用
Converter
: the sample 我发现它描述了布尔值的可见性,但您可以根据需要更改它。
我发现很难让我的列表视图项目显示其他颜色。最后,我设法通过为 ListView 事件处理程序 ContainerContentChanging 分配一个方法来做到这一点。
当每个项目都填充到列表视图中时,将调用分配给此事件的方法。这提供了更改列表视图项目的前景、背景、文本等的功能
private void listViewContentChange(ListViewBase sender, ContainerContentChangingEventArgs args) {
//this method is called for each item while it gets loaded in the listview. Here we are changing background color and text color
if (args.ItemIndex == 0) {
//colour for header
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["grey"];
} else {
if (args.ItemIndex % 2 == 0) {
//lighter colour
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["lightblue"];
} else {
//Dark colour
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["blue"];
}
}
编辑:UWP 应用与 WPF 应用并非 100% 相同。
我有一个带有 ListView 的 uwp 应用程序。在 ListView 中,我使用带有 class 测试的 DataTemplate。它显示测试的名称和分数。
我想要完成的是一个触发器!?检查点数是否大于即:50,然后将 ListViewItem 的背景颜色更改为红色。
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Tests">
<Grid>
<TextBlock Text="{x:Bind Name}" />
<TextBlock Text="{x:Bind Points}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
您可以使用类似的东西:
在那个例子中,海报只是检查它是偶数还是奇数,以创建交替颜色。
if (index % 2 == 0)
{
...
}
在你的情况下,你可以这样做:
if(item.Points > 50)
{
return this.RedBackgroundStyle;
}
您可以通过多种方式做到这一点:
- 使用
ItemContrainerStyleSelector
: the sample 我找到了 - 使用
DataTemplateSelector
: the sample 我找到了 - 使用
Converter
: the sample 我发现它描述了布尔值的可见性,但您可以根据需要更改它。
我发现很难让我的列表视图项目显示其他颜色。最后,我设法通过为 ListView 事件处理程序 ContainerContentChanging 分配一个方法来做到这一点。
当每个项目都填充到列表视图中时,将调用分配给此事件的方法。这提供了更改列表视图项目的前景、背景、文本等的功能
private void listViewContentChange(ListViewBase sender, ContainerContentChangingEventArgs args) {
//this method is called for each item while it gets loaded in the listview. Here we are changing background color and text color
if (args.ItemIndex == 0) {
//colour for header
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["grey"];
} else {
if (args.ItemIndex % 2 == 0) {
//lighter colour
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["lightblue"];
} else {
//Dark colour
args.ItemContainer.Background = (SolidColorBrush) Application.Current.Resources["blue"];
}
}