[SOLVED] Change Background Color of ListView Selected Item in Xamarin

Issue

I created a Master-Detail type project in Xamarin. When I selected an item from the Master page the background color is orange by default. How can I change this to a color of my choosing?

Solution

You can bind BackgroundColor for ContentView of ViewCell , then use ViewModel and ItemTapped method of ListView to modify the selected item background color .

For example , the xaml code as follow´╝Ü

<ListView x:Name="ListViewMenu"
            HasUnevenRows="True" ItemTapped="ListViewMenu_ItemTapped">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell >
                <Grid Padding="10"
                        BackgroundColor="{Binding SelectedBackgroundColor}">
                    <Label Text="{Binding Title}" d:Text="{Binding .}" FontSize="20"/>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Then in HomeMenuItem model add SelectedBackgroundColor property :

public enum MenuItemType
{
    Browse,
    About
}
public class HomeMenuItem : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public MenuItemType Id { get; set; }

    public string Title { get; set; }

    private Color selectedBackgroundColor;
    public Color SelectedBackgroundColor
    {
        set
        {
            if (selectedBackgroundColor != value)
            {
                selectedBackgroundColor = value;
                OnPropertyChanged("SelectedBackgroundColor");
            }
        }
        get
        {
            return selectedBackgroundColor;
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}

Then in MenuPage modify ItemSource as follow:

public partial class MenuPage : ContentPage
{
    MainPage RootPage { get => Application.Current.MainPage as MainPage; }
    List<HomeMenuItem> menuItems;
    List<HomeMenuItem> tmpItems; // add a tmp list to remove setted backgroud color
    public MenuPage()
    {
        InitializeComponent();

        tmpItems = new List<HomeMenuItem>();
       
        menuItems = new List<HomeMenuItem>
        {
            new HomeMenuItem {Id = MenuItemType.Browse, Title="Browse" },
            new HomeMenuItem {Id = MenuItemType.About, Title="About" }
        };

        menuItems[0].SelectedBackgroundColor = Color.Red; // default set the first item be selected, you can modify as your wants
        tmpItems.Add(menuItems[0]); // add the selected item (default is the first)

        ListViewMenu.ItemsSource = menuItems;

        ListViewMenu.SelectedItem = menuItems[0];
        ListViewMenu.ItemSelected += async (sender, e) =>
        {
            if (e.SelectedItem == null)
                return;

            var id = (int)((HomeMenuItem)e.SelectedItem).Id;
            await RootPage.NavigateFromMenu(id);
        };
    }

    private void ListViewMenu_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        menuItems[e.ItemIndex].SelectedBackgroundColor = Color.Red;
        tmpItems[0].SelectedBackgroundColor = Color.Transparent;
        tmpItems[0] = menuItems[e.ItemIndex];
    }
}

The effect :

enter image description here
enter image description here

Answered By – Junior Jiang

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *