How to turn Events into Commands with Behaviors in Xamarin.Forms Tabbed View?
The Xamarin.Forms SfTabview events can be used in MVVM approach, by using the “EventToCommand” behavior.
Here, we have created a Command for SelectionChanged event of Xamarin.Forms.SfTabView in ViewModel.
ViewModel:
public class MainPageViewModel {
public Command SelectionChangedCommand { get; set; }
public MainPageViewModel() { SelectionChangedCommand = new Command<Syncfusion.XForms.TabView.SelectionChangedEventArgs>(TabViewSelectionChanged); }
public void TabViewSelectionChanged(Syncfusion.XForms.TabView.SelectionChangedEventArgs selectionChangedEventArgs) { // Do action App.Current.MainPage.DisplayAlert("Alert", "You have been selected " + selectionChangedEventArgs.Name + "Tab", "OK"); } } |
XAML:
<ContentPage.Content> <tabView:SfTabView BackgroundColor="Aqua"> <tabView:SfTabView.Behaviors> <behaviors:EventToCommandBehavior Command="{Binding SelectionChangedCommand}" EventName="SelectionChanged"/> </tabView:SfTabView.Behaviors>
<tabView:SfTabItem Title="Call"> <tabView:SfTabItem.Content> <Grid BackgroundColor="Red" x:Name="AllContactsGrid" /> </tabView:SfTabItem.Content> </tabView:SfTabItem> </ContentPage.Content> |
Now, when tapped on the TabItem, corresponding Command in ViewModel will be invoked automatically and performed the desired operation as shown in the followingbelow screenshot.
Screenshot:
Sample :
https://www.syncfusion.com/downloads/support/directtrac/general/ze/TabViewCommand308061808.zip