CollectionView: change selected Label textcolor

Alessandro Caliaro 4,196 Reputation points
2021-02-03T10:48:42.733+00:00

CollectionView Selected Item Highlight Colour

In this example is it possible to change the Grid background color when the items is selected.
I would like to change the grid background color AND the Label TextColor

Is it possibile with VisualStateManager?

Developer technologies | .NET | Xamarin
{count} vote

Accepted answer
  1. JarvanZhang 23,971 Reputation points
    2021-02-03T12:23:20.06+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    We can also use VisualStateManager.VisualStateGroups to achieve the function. Try adding x:Name for the Label view and then use <Setter TargetName="xx" /> to set style for the label.

    Check the code:

       <CollectionView SelectionMode="Single" ...>  
           <CollectionView.ItemTemplate>  
               <DataTemplate>  
                   <Grid>  
                       <VisualStateManager.VisualStateGroups>  
                           <VisualStateGroup Name="CommonStates">  
                               <VisualState Name="Normal" />  
                               <VisualState Name="Selected">  
                                   <VisualState.Setters>  
                                       <Setter Property="BackgroundColor" Value="Yellow" />  
                                       <Setter TargetName="_label" Property="Label.TextColor" Value="Red" />  
                                   </VisualState.Setters>  
                               </VisualState>  
                           </VisualStateGroup>  
                       </VisualStateManager.VisualStateGroups>  
         
                       <Label x:Name="_label" Text="{Binding xx}"/>  
                   </Grid>  
               </DataTemplate>  
           </CollectionView.ItemTemplate>  
       </CollectionView>  
    

    Related doc: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual-state-manager#define-your-own-visual-states

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.