Data Binding in .NET MAUI ComboBox
-
ItemsSource
(IEnumerable
)—Defines the collection of the items that will populate the control with data. -
DisplayMemberPath
(string
)—Defines the name of the property which will be visualized inside the drop-down list.
If DisplayMemberPath is not set the “ToString” implementation of the business object will be visualized. The DisplayMemberPath is a property that helps the developers to visualize an exact property from the business object they are bound to.
Binding to a Complex Object
1. Define the ComboBox in XAML:
<telerik:RadComboBox ItemsSource="{Binding Items}"
DisplayMemberPath="Population"
AutomationId="boundComboBox"/>
2. Add the telerik
namespace:
xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
4. Add the ViewModel:
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<City>
{
new City { Name = "Tokyo", Population = 13929286 },
new City { Name = "New York", Population = 8623000 },
new City { Name = "London", Population = 8908081 },
new City { Name = "Madrid", Population = 3223334 },
new City { Name = "Los Angeles", Population = 4000000},
new City { Name = "Paris", Population = 2141000 },
new City { Name = "Beijing", Population = 21540000 },
new City { Name = "Singapore", Population = 5612000 },
new City { Name = "New Delhi", Population = 18980000 },
new City { Name = "Bangkok", Population = 8305218 },
new City { Name = "Berlin", Population = 3748000 },
};
}
public ObservableCollection<City> Items { get; set; }
}
5. Set the binding context after InitializeComponent()
in the page's code behind:
this.BindingContext = new ViewModel();