Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>

like image 345
Richi S. Avatar asked Oct 14 '25 11:10

Richi S.


1 Answers

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.

enter image description here

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"];
              }
            }
like image 140
ficocons Avatar answered Oct 17 '25 01:10

ficocons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!