How to add new items to SfComboBox dynamically?
You can add items dynamically to SfComboBox by adding a Xamarin.Forms button on DropDownFooterView. You need to add text, which is present on the SfComboBox, to its ItemsSource by clicking that button. Please follow the given steps to add items on SfComboBox dynamically:
Step 1: Add the necessary assemblies to the .NET Standard, Android, iOS, and UWP projects. Refer to this UG documentation to know more about the assemblies required for adding SfComboBox to your project.
Step 2: Create the SfComboBox control with DropDownFooter view as demonstrated in the following code.
XAML
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:combobox="clr-namespace:Syncfusion.XForms.ComboBox;assembly=Syncfusion.SfComboBox.XForms" xmlns:comboboxitems="clr-namespace:ComboBoxItems" x:Class="ComboBoxItems.MainPage"> <ContentPage.BindingContext> <comboboxitems:ViewModel/> </ContentPage.BindingContext> <StackLayout> <combobox:SfComboBox x:Name="comboBox" NoResultsFoundText="No Result Found" DropDownFooterViewHeight="40" AllowFiltering="True" IsEditableMode="True" DataSource="{Binding Collection, Mode=TwoWay}" Watermark="Please enter note"> <combobox:SfComboBox.DropDownFooterView> <Button x:Name="btn" FontSize="14" HeightRequest="40" Text="Add New Item" Command="{Binding AddItem}" CommandParameter="{Binding Source={x:Reference comboBox}, Path=Text}"/> </combobox:SfComboBox.DropDownFooterView> </combobox:SfComboBox> </StackLayout> </ContentPage>
Step 3: On the button click, add the text present in the SfComboBox to its ItemsSource. On ViewModel, use the following code.
ViewModel
public class ViewModel { public ICommand AddItem { get; private set; } private ObservableCollection<string> collection; public ObservableCollection<string> Collection { get { return collection; } set { collection = value; } } public ViewModel() { Collection = new ObservableCollection<string>(); Collection.Add("Item1"); Collection.Add("Item2"); Collection.Add("Item3"); Collection.Add("Item4"); Collection.Add("Item5"); Collection.Add("Item6"); Collection.Add("Item7"); Collection.Add("Item8"); AddItem = new Command<string>(AddListItems); } void AddListItems(string value) { Collection.Add(value); } }
When the button inside the DropDownFooterView is clicked, the text inside the SfComboBox will be added to its collection.
You can download the sample in this link.
Output image:
|