uwp: how to change background color of listview item based on its value?

浪尽此生 提交于 2019-12-22 10:29:56

问题


Edit: UWP App is not 100% the same like the WPF App.

I have a uwp App with a ListView. In the ListView i use a DataTemplate with the class of Tests. It displays the name of the Test and Points.

What i want to accomplish is that a Trigger !? checks if the Points are greater than i.e.: 50 and then change the background color of the ListViewItem to red.

            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:Tests">
                    <Grid>
                        <TextBlock Text="{x:Bind Name}"  />
                        <TextBlock Text="{x:Bind Points}"  />
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>


回答1:


You can do this in several ways:

  1. Use ItemContrainerStyleSelector: the sample which I found
  2. Use DataTemplateSelector: the sample which I found
  3. Use Converter: the sample which I found describes bool to visibility, but you can change it like you want.



回答2:


I was finding it hard to get my listview items to show alternative colours. Finally I managed to do this by assigning a method to the ListView event handler ContainerContentChanging.

The method assigned to this event gets called when each item gets populated in the listview. This provides a capability to change foreground, background, text, etc for the listview item

        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"];
              }
            }



回答3:


You can use something similar to this: https://stackoverflow.com/a/27621234/3869250

In that example, the poster just checked if it was even or odd, to create alternating colors.

if (index % 2 == 0)
{
    ...
}

In your case, you could do something like:

if(item.Points > 50)
{
    return this.RedBackgroundStyle;
}



回答4:


have a look at that full code snippet answer about alternate colors.



来源:https://stackoverflow.com/questions/35346001/uwp-how-to-change-background-color-of-listview-item-based-on-its-value

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