Xamarin Forms Listview selecteditem设置backgroundcolor第一次不工作

时间:2017-07-26 11:59:30

标签: c# xamarin.forms

我有一个CustomViewRenderer,它可以更改Listview中项目的Backgroundcolor。 如果我单击某个项目,颜色更改正确。 当我加载ListView并以编程方式设置ItemSource和SelectedItem时,Color是Android中的标准橙色。 ListView.SelectedItem在第一次加载时不会调用Android渲染器“OnCellPropertyChanged”。

我的错误是什么?

加载ListView:

listNew = listDG.Where(g => g.check == true).ToList();
        listNew = listNew.OrderBy(g => g.beschreibung).ToList();
        listGegenstandZuordnungBinding = new BindingList<db.gegenstaendezuordnungliste>(listNew);
        lvGegenstaende.ItemsSource = listGegenstandZuordnungBinding;
        lvGegenstaende.ItemSelected += LvGegenstaende_ItemSelected; ;

        if (App.idgegenstandueb != 0)
        {
            List<db.gegenstaendezuordnungliste> listSelected = listNew.Where(g => g.idgegenstandueb == App.idgegenstandueb).ToList();
            if (listSelected.Count > 0)
            {
                lvGegenstaende.SelectedItem = listSelected[0];
            }
            else
            {
                if (listNew.Count > 0)
                {
                    lvGegenstaende.SelectedItem = listNew[0];
                    App.idgegenstandueb = listNew[0].idgegenstandueb;
                }
            }
        }
        else if (listNew.Count > 0)
        {
            App.idgegenstandueb = listNew[0].idgegenstandueb;
            lvGegenstaende.SelectedItem = listNew[0];
        }

Android渲染器:

protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
    {
        var listView = parent as Android.Widget.ListView;
        _selected = false;
        if (listView != null)
        {
            //    // Disable native cell selection color style - set as *Transparent*
            listView.SetSelector(Android.Resource.Color.Transparent);
            listView.CacheColorHint = Xamarin.Forms.Color.Transparent.ToAndroid();
        }
        var cell = base.GetCellCore(item, convertView, parent, context);
        return cell;
    }

    protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnCellPropertyChanged(sender, e);

        _selected = !_selected;

        var extendedViewCell = sender as CustomControl;
        if (extendedViewCell.Parent.AutomationId != null)
        {
            if (extendedViewCell.Parent.AutomationId.ToString() == "Listgegenstaende")
            {
                if (_selected)
                    extendedViewCell.View.BackgroundColor = Color.FromHex("4682B4");
                else
                    extendedViewCell.View.BackgroundColor = Color.FromHex("#5096D0");
            }
        }
        else
        {
            if (_selected)
                extendedViewCell.View.BackgroundColor = Color.Black;
            else
                extendedViewCell.View.BackgroundColor = Color.Transparent;
        }
    }

0 个答案:

没有答案