Category / Section
How to apply the item text color in .NET MAUI ListView (SfListView) ?
1 min read
You can apply different text color to the element loaded within the ItemTemplate by using the TextColor property with converter in .NET MAUI ListView (SfListView).
XAML
Define the converter for the Label.TextColor.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ListViewMaui.MainPage" xmlns:local="clr-namespace:ListViewMaui" xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView" BackgroundColor="{DynamicResource SecondaryColor}"> <ContentPage.BindingContext> <local:ContactsViewModel/> </ContentPage.BindingContext> <ContentPage.Resources> <ResourceDictionary> <local:ColorConverter x:Key="ColorConverter"/> </ResourceDictionary> </ContentPage.Resources> <ContentPage.Content> <syncfusion:SfListView x:Name="listView" ItemSize="60" ItemsSource="{Binding ContactsInfo}"> <syncfusion:SfListView.ItemTemplate > <DataTemplate> <Grid x:Name="grid"> … <Image Source="{Binding ContactImage}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="50" WidthRequest="50"/> <Grid Grid.Column="1" RowSpacing="1" Padding="10,0,0,0" VerticalOptions="Center"> <Grid.RowDefinitions> <RowDefinition Height="25"/> <RowDefinition Height="20"/> </Grid.RowDefinitions> <Label LineBreakMode="NoWrap" FontFamily="RobotoMedium" Grid.Row="0" TextColor="{Binding .,Converter={StaticResource ColorConverter},ConverterParameter={x:Reference Name=listView}}" Text="{Binding ContactName}"/> <Label Grid.Row="1" FontFamily="RobotoMedium" Grid.Column="0" TextColor="{Binding .,Converter={StaticResource ColorConverter},ConverterParameter={x:Reference Name=listView}}" LineBreakMode="NoWrap" Text="{Binding ContactNumber}"/> </Grid> <Label Grid.Column="2" TextColor="{Binding .,Converter={StaticResource ColorConverter},ConverterParameter={x:Reference Name=listView}}" LineBreakMode="NoWrap" Text="{Binding ContactType}" FontFamily="RobotoMedium" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/> </Grid> </DataTemplate> </syncfusion:SfListView.ItemTemplate> </syncfusion:SfListView> </ContentPage.Content> </ContentPage>
C#
Returns TextColor based on the ContactType property.
public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return false; var itemdata = value as Contacts; if (itemdata.ContactType == "HOME") return Colors.RoyalBlue; else if (itemdata.ContactType == "WORK") return Colors.PaleGreen; else if (itemdata.ContactType == "MOBILE") return Colors.HotPink; else if (itemdata.ContactType == "OTHER") return Colors.DarkGoldenrod; else return Colors.BlueViolet; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }