Change Label’s TextColor in a ListView’s SelectedItem, obviously in Xamarin Forms

ListView is a common control in a Xamarin Forms Project. It works pretty nice. When you select an Item in the list, the row change its color so you understand that it’s the “Selected” row.

Sometimes there is the need to change the color of the text, non only the color of the row (that is automatically changed by the selection). How can I do this?

I have found this solution. Maybe not be the optimal solution… the debate is open!

Step 1: create a Selected property

Your Model should know that the Item is selected, so there should be something like

public bool Selected { get; set; }

Step 2: your ViewModel should understand which is the SelectedItem

In ViewModel you have to know which is the SelectedItem in your ListView. Create a property

MyModel _selectedItem { get; set; }

then, use it

public MyModel SelectedItem
 {
    get { return _selectedItem; }
    set
    {
        if (_selectedItem != null)
            _selectedItem.Selected = false;

        _selectedItem = value;

        if (_selectedItem != null)
            _selectedItem.Selected = true;
    }
 }

What happens? When your Item is selected in the ListView, the SelectedItem property will change (because it will be bind to ListView’s “ItemSelect” property). The “old” _selectedItem will be unselected (Selected = false), and the “new” _selectedItem will be selected (Selected = true)

Step 3: set the correct binding in XAML

We use a XAML file (I don’t use XAML in my projects, but today I feel fine and I am ready to write some < />. My friend Thomas will be happy) to create our UI:

<?xml version="1.0" encoding="utf-8"?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        xmlns:local="clr-namespace:TestSelectedItemInListView" 
        x:Class="TestSelectedItemInListView.TestSelectedItemInListViewPage">
        <ContentPage.Resources>
            <ResourceDictionary>
                <local:SelectedToColorConverter x:Key="cnvInvert">                                  </local:SelectedToColorConverter>
          </ResourceDictionary>
        </ContentPage.Resources>

        <Label Text="Welcome to Xamarin Forms!" VerticalOptions="Center" HorizontalOptions="Center" />
        <ListView SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding List}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding Name}" TextColor="{Binding Selected, Converter={StaticResource cnvInvert}}}" FontSize="18"></Label>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

There is a ListView that has an ItemSource (List is defined in the ViewModel, an ObservableCollection of course). The ListView’s SelectedItem property has a binding with the SelectedItem in the ViewModel.

The DataTemplate is a ViewCell with a Label. The Label has some Binding:

  • The Text property (in binding with Name property in the Model)
  • The TextColor property (in binding with Selected property in the Model)

Do you see something strange? Yes, the Boolean property “Selected” has been bind to a non Boolean property “TextColor”. Is it possible? The answer is YES, because we use a IValueConverter, that Convert a value to another (in this case, a Boolean value to a Xamarin.Forms.Color value)

Step 4: the IValueConverter interface

public class SelectedToColorConverter : IValueConverter
 {

    #region IValueConverter implementation

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)
        {
            if ((Boolean)value)
                return Color.Orange;
            else
                return Color.Black;
        }
        return Color.Black;
    }

    public object ConvertBack(object value, Type targetType, object parameter,    System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
 }

When Selected property is TRUE, the TextColor is Orange, otherwise it is Black. You can find more info about Data Binding in this article. This mode can be used to change also other properties in the ViewCell (for example, the background color of some fields).

I hope to have write all, otherwise comment this article so I can update it.

I hope my english is a little better every article I write (please don’t comment about this…).

You can find a repo on GitHub.

 

 

 

Annunci

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...