How to add image and label in the dropdown item in SfComboBox
Syncfusion ComboBox is a text box component; it allows users type a value or choose an option from a list of predefined options. It provides ItemTemplate support. This document explains how to add images and labels in drop-down.
The following steps explain how to add an image and label to ComboBox item.
Step 1: Create a ComboBox sample with all the required assemblies.
Step 2: Add the necessary images in the required folder to each project that has to be shown in the drop-down list
Android: Resource > drawable
iOS: Resource
UWP: Add the images inside the project.
Step 3: Create the Model class with the properties need to be assigned.
Model
public class Employee
{
private string image;
public string Image
{
get { return image; }
set { image = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
Step 4: Create the ViewModel class and add a collection that needs to be bound with the data source.
ViewModel
public class EmployeeViewModel
{
private ObservableCollection<Employee> employeeCollection;
public ObservableCollection<Employee> EmployeeCollection
{
get { return employeeCollection; }
set { employeeCollection = value; }
}
public EmployeeViewModel()
{
employeeCollection = new ObservableCollection<Employee>();
employeeCollection.Add(new Employee() { Image = "image1.png", Name = "Frank" });
employeeCollection.Add(new Employee() { Image = "image2.png", Name = "James" });
employeeCollection.Add(new Employee() { Image = "image3.png", Name = "Steve" });
employeeCollection.Add(new Employee() { Image = "image4.png", Name = "Lucas" });
employeeCollection.Add(new Employee() { Image = "image5.png", Name = "Mark" });
}
}
Step 5: Initialize the ComboBox control in the xaml page in which the ViewModel class is set to BindingContext.
XAML
<ContentPage.BindingContext>
<local:EmployeeViewModel />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="itemTemplate">
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand" Padding="5,0,0,0">
<Image Source="{Binding Image}" HeightRequest="40" WidthRequest="40" Aspect="AspectFit" />
<Label Text="{Binding Name}" TextColor="Black" VerticalTextAlignment="Center" HorizontalOptions="Center" FontSize="Medium" WidthRequest="200" />
</StackLayout>
</DataTemplate>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout VerticalOptions="Start" HorizontalOptions="Start" Padding="30">
<combobox:SfComboBox x:Name="comboBox" ItemTemplate="{StaticResource itemTemplate}" DropDownItemHeight="45" Watermark="Select Employees" DataSource="{Binding EmployeeCollection}">
</combobox:SfComboBox>
</StackLayout>
</ContentPage.Content>
Output:
|
The sample for the above code snippet is given on this link
