Hello,
Welcome to our Microsoft Q&A platform!
CustomeViewCellRenderer doesn't work when set CachingStrategy="RecycleElement"
This is because when developers specify RecycleElement, OnElementChanged events will not raised when cells are recycled. Check the doc:
https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.listviewcachingstrategy?view=xamarin-forms#Xamarin_Forms_ListViewCachingStrategy_RetainElement
To change the background color of the selected items, try to set data binding for the BackgroundColor of the item's layout control. Then detect the ItemTapped to update the value.
<ListView ItemsSource="{Binding DataCollection}" ItemTapped="ListView_ItemTapped" CachingStrategy="RecycleElement">
<ListView.ItemTemplate >
<DataTemplate>
<ViewCell>
<StackLayout BackgroundColor="{Binding SelectedColor}">
<!--the views-->
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
//page.xaml.cs
public partial class TestPage : ContentPage
{
TestPageViewModel viewModel;
public TestPage()
{
InitializeComponent();
viewModel = new TestPageViewModel();
BindingContext = viewModel;
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
foreach (var item in viewModel.DataCollection)
{
item.SelectedColor = Color.White;
}
var model = e.Item as TestPageModel;
model.SelectedColor = Color.Red;
}
}
//model class
public class TestPageModel : INotifyPropertyChanged
{
...
private Color selectedColor;
public Color SelectedColor
{
get
{
return selectedColor;
}
set
{
if (selectedColor != value)
{
selectedColor = value;
NotifyPropertyChanged("SelectedColor");
}
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.