How to use Behaviours for SelectionChanged event in Autocomplete control
You can use Behaviors for the SelectionChanged event of the SfAutoComplete control by following the given steps:
Step 1: Add the necessary assemblies in the PCL, Android, iOS, and UWP projects. Refer to this UG documentation to know more about the assemblies required for adding SfAutoComplete control to your project.
Step 2: Add the SfAutoComplete control to the content view of the main page using the following code.
XAML
<StackLayout Padding="50,100,50,0"> <autocomplete:SfAutoComplete x:Name="autocomplete" MultiSelectMode="Token" DisplayMemberPath="Name" DataSource="{Binding EmployeeCollection}" SelectedItem="{Binding MultiSelectedItem,Mode=TwoWay}" > </autocomplete:SfAutoComplete> </StackLayout>
Step 3: Add the necessary Model and ViewModel classes and add the following binding context on the MainPage.Cs page.
C#
namespace ComboBox { public partial class MainPage : ContentPage { EmployeeViewModel employeeViewModel; public MainPage() { InitializeComponent(); employeeViewModel = new EmployeeViewModel(); this.BindingContext = employeeViewModel; } } }
Step 4: Add the Behavior code in the view model that needs to be used for auto complete SelectionChangedEvent.
C#
public class SelectionChangedBehavior : Behavior<SfAutoComplete> { public Command Display {get; private set; } EmployeeViewModel employeeViewModel; protected override void OnAttachedTo(SfAutoComplete bindable) { bindable.SelectionChanged += Bindable_SelectionChanged; base.OnAttachedTo(bindable); } protected override void OnDetachingFrom(SfAutoComplete bindable) { bindable.SelectionChanged -= Bindable_SelectionChanged; base.OnDetachingFrom(bindable); } void Bindable_SelectionChanged(object sender, Syncfusion.SfAutoComplete.XForms.SelectionChangedEventArgs e) { employeeViewModel = new EmployeeViewModel(); var selectedValue = e.Value as List<object>; var lastItem = selectedValue.Last(); employeeViewModel.SelectedId = new List<string>(); foreach (var item in selectedValue) { if (item == lastItem) { var selId = item as Employee; employeeViewModel.SelectedId.Add(selId.Id); Application.Current.MainPage.DisplayAlert("Selected Id", "The last selected ID is " + selId.Id, "Ok"); } else { var selId = item as Employee; employeeViewModel.SelectedId.Add(selId.Id); } } } }
Add the same behavior to your SfAutoComplete Xaml code.
XAML
<StackLayout Padding="50,100,50,0"> <autocomplete:SfAutoComplete x:Name="autocomplete" MultiSelectMode="Token" DisplayMemberPath="Name" DataSource="{Binding EmployeeCollection}" SelectedItem="{Binding MultiSelectedItem,Mode=TwoWay}" > <autocomplete:SfAutoComplete.Behaviors> <local:SelectionChangedBehavior/> </autocomplete:SfAutoComplete.Behaviors> </autocomplete:SfAutoComplete> </StackLayout>
The following screenshot illustrates the output.
|
You can download the sample for using Behaviors for the SelectionChanged event of SfAutoComplete in the following link: Sample