Hello,
I am creating a list. I need each item in the list to have a different background color. With the code I'm using the background color is white. I'm not sure what I'm doing wrong.
using Xamarin.Forms;
namespace App5
{
public partial class MainPage : ContentPage
{
public class ListItem
{
public string Title { get; set; }
public Color ForeColor { get; set; }
public Color BackgroundColor { get; set; }
}
public MainPage()
{
InitializeComponent();
var listView = new ListView();
listView.ItemsSource = new ListItem[] {
new ListItem {Title ="Red", ForeColor = Color.White, BackgroundColor = Color.Red},
new ListItem {Title ="Orange", ForeColor = Color.White, BackgroundColor = Color.Orange},
new ListItem {Title ="Yellow", ForeColor = Color.White, BackgroundColor = Color.Yellow},
new ListItem {Title ="Green", ForeColor = Color.White, BackgroundColor = Color.Green},
new ListItem {Title ="Blue", ForeColor = Color.White, BackgroundColor = Color.Blue},
new ListItem {Title ="Violet", ForeColor = Color.White, BackgroundColor = Color.Violet}
};
listView.RowHeight = 80;
listView.ItemTemplate = new DataTemplate(typeof(ListItemCell));
Content = listView;
listView.ItemTapped += async (sender, e) => {
ListItem item = (ListItem)e.Item;
await DisplayAlert("Tapped", item.Title.ToString() + " was selected.", "Ok");
((ListView)sender).SelectedItem = null;
};
}
class ListItemCell : ViewCell
{
public ListItemCell()
{
Label titleLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
FontSize = 25,
FontAttributes = Xamarin.Forms.FontAttributes.Bold,
TextColor = Color.White
};
titleLabel.SetBinding(Label.TextProperty, "Title");
StackLayout viewLayoutItem = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { titleLabel}
};
StackLayout viewLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Horizontal,
Padding = new Thickness(25, 10, 55, 15),
Children = { viewLayoutItem }
};
View = viewLayout;
}
}
}
}