列表中每个选择的背景色不同

时间:2019-03-31 23:28:42

标签: c# xamarin

我正在创建一个列表,并且列表中的每个项目都需要不同的背景色。有了代码,我的背景颜色是白色。我缺少什么。

    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;
        }
    }
}

}

好吧,经过更多的研究,我意识到我对原色和背景色缺少约束力。现在就去弄清楚那块。

1 个答案:

答案 0 :(得分:0)

我弄清楚了我所缺少的。之所以选择前景色,是因为我能够以不同的方式设置文本颜色,因为所有文本都是一种颜色。

至于背景,我错过了:

viewLayout.SetBinding(StackLayout.BackgroundColorProperty,“ BackgroundColor”);

现在可以使用了:)