JsonDork
JsonDork

Reputation: 718

How to dynamically change the colour of label? Xamarin

I got this code below but I can't figure out how to make the selected label be turned into blue background colour and white text instead of what it has in unselected mode. There can only be 1 journey selected at time, and the one that is selected needs to be modified. I figured I could use datatriggers or behaviours. I can figure out how to change the button in the command, but how would I change the other buttons? that gets unselected into gray?

<CollectionView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding JourneyItems}" SelectionMode="Single"  ItemsLayout="{x:Static ListItemsLayout.HorizontalList}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Horizontal" >
                <StackLayout Margin="10,0,10,0" BackgroundColor="LightGray"  VerticalOptions="Fill"  Orientation="Horizontal" >
                    <Label Text="{Binding Name}"  TextColor="{StaticResource ThemeBkColor}" VerticalTextAlignment="Center" VerticalOptions="Center" />
                </StackLayout>

                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding Path=ViewModel.SwitchJourneyCommand, Source={x:Reference ThisJourneysPage}}"
                        CommandParameter = "{Binding .}" NumberOfTapsRequired="1"/>
                </StackLayout.GestureRecognizers>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Upvotes: 0

Views: 2922

Answers (1)

hvaughan3
hvaughan3

Reputation: 11105

You just need to add a Selected property to your JourneyItems model and then even a BackgroundColor.

public class JourneyItem {
    // more stuff

    public bool Selected { get; set; }

    public Color BackgroundColor => Selected ? Color.Blue : Color.Gray;

    public Color TextColor => Selected ? Color.White : Color.Black;
}

Then bind the BackgroundColor and TextColor to change to color X when Selected is true and color Y otherwise.

<Label Text="{Binding Name}"  TextColor="{Binding TextColor}"  BackgroundColor="{Binding BackgroundColor}"/>

Finally, in ViewModel.SwitchJourneyCommand set your selected model to true and all other models to false.

public void OnJourneyCommand(JourneyItem selectedItem) {
    foreach(JourneyItem item in JourneyItems) {
        item.Selected = item.Id == selectedItem.Id;
    }
}

*Edit: To be clear, this will not automatically change colors when Selected is changed. Object properties do not automatically bubble up as change events. To do that, you would want to add property changed events to the Selected property and have it trigger a change on BackgroundColor and TextColor when Selected gets toggled. Something like this: https://stackoverflow.com/a/39350109/3850012

Upvotes: 1

Related Questions