I needed to change the color of the selected item in ListView in my Xamarin.Forms application, so I implemented a custom rendered for ViewCell. This worked as required, untill I filled my list with so many elements, that it had to be scrolled. After scroll occurres on the list, it causes a weird bug, where more than one row gets selected (just as if scrolling the list, would change the scope where list looks for selected items and did not reset the selected item). My best guess is that I need to extend my renderer to count for the scrolling of ListView, but I have no idea how to do this. Has anyone encountered similar issues?
Custom Renderer:
[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace MyApp.Droid.PlatformSpecific.Renderers
{
public class ExtendedViewCellRenderer : ViewCellRenderer
{
private Android.Views.View _cellCore;
private Drawable _unselectedBackground;
private bool _selected;
protected override Android.Views.View GetCellCore(Cell item,
Android.Views.View convertView,
ViewGroup parent,
Context context)
{
_cellCore = base.GetCellCore(item, convertView, parent, context);
_selected = false;
_unselectedBackground = _cellCore.Background;
return _cellCore;
}
protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.OnCellPropertyChanged(sender, args);
if (args.PropertyName == "IsSelected")
{
_selected = !_selected;
if (_selected)
{
var extendedViewCell = sender as ExtendedViewCell;
_cellCore.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid());
}
else
{
_cellCore.SetBackground(_unselectedBackground);
}
}
}
}
}
Custom ViewCell:
public class ExtendedViewCell : ViewCell
{
public static readonly BindableProperty SelectedBackgroundColorProperty =
BindableProperty.Create("SelectedBackgroundColor",
typeof(Color),
typeof(ExtendedViewCell),
Color.Default);
public Color SelectedBackgroundColor
{
get { return (Color)GetValue(SelectedBackgroundColorProperty); }
set { SetValue(SelectedBackgroundColorProperty, value); }
}
}
Update: I have managed to trace down the issue to beeing caused by different implementation of caching on newer Xamarin.Forms versions. Even the author of the above solution haven't managed to solve this out at this moment: Link