Daniel Hindrikes
Developer and architect with focus on mobile- and cloud solutions!
Developer and architect with focus on mobile- and cloud solutions!
The ListView control in Xamarin.Forms has a background color property. But iOS has a default color on each cell, because of that it will not work to set a color with that property. One solution is to use a custom renderer for the ListView on iOS.
A custom renderer can be created for the ListView control, but I prefer to create a new control that inherit from ListView. Then I can use the ListView as standard as I want and I can use my customized ListView if I want.
The first step i to create a new control that inherits from ListView.
public class MyListView : ListView
{
}
Next step is to create the CustomRenderer for iOS. To do that create a new class in your iOS project (If you don't create a custom ListView for the other platforms, the standard renderer will be used). Your new class will inherit from ListViewRenderer. In the custom renderer you will override the OnElementPropertyChanged method.
In this method you can do the changes you want to do to the ListView. This code will run every time a property is changed on the ListView. In this case we only need to run our code when it's the ItemsSource property that is changed.
public class MyListViewRenderer : ListViewRenderer
{
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName == "ItemsSource")
{
var control = (UITableView)Control;
foreach (var cell in control.VisibleCells)
{
cell.BackgroundColor = UIColor.FromRGB(255, 0, 0);
}
}
}
}
To use the custom renderer we need to add an assembly attribute outside the class and the namespace.
[assembly: ExportRenderer(typeof(MyListView), typeof(MyListViewRenderer))]
namespace MyApp.iOS
{
To use your new control i your XAML you need to include the namespace for it.
Then you can use it with the alias you assign to it in the namespace declaration.