Category / Section
How to fire the events in SfDataGrid by using the commands defined in the ViewModel?
1 min read
Events in SfDataGrid can be fired by using commands with the help of Xamarin.Forms.Behaviors. The Xamarin.Forms.Behaviors allows you to convert events into commands. To use it, you need to install the Xamarin.Forms.Behaviours NuGet in your application which can be find in the below link.
NuGet Link: https://www.nuget.org/packages/Xamarin.Forms.Behaviors/
Refer the below code example in which Xamarin.Forms.Behaviors has been used to convert the SelectionChanged event in SfDataGrid into command.
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" x:Class="SampleDemo.XamlPage" xmlns:local ="clr-namespace:SampleDemo;assembly=SampleDemo" xmlns:b="clr-namespace:Xamarin.Behaviors;assembly=Xamarin.Behaviors" xmlns:sf="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"> <ContentPage.BindingContext> <local:ViewModel x:Name="viewModel" /> </ContentPage.BindingContext> <sf:SfDataGrid x:Name="dataGrid" AutoGenerateColumns="true" ColumnSizer="Star" SelectionMode="Single" ItemsSource ="{Binding OrderInfo}"> <b:Interaction.Behaviors> <b:BehaviorCollection> <b:EventToCommand EventName="SelectionChanged" Command="{Binding SelectionCommand}" /> </b:BehaviorCollection> </b:Interaction.Behaviors> </sf:SfDataGrid> </ContentPage>
ViewModel.cs
private Command selectionCommand; public Command SelectionCommand { get { return selectionCommand; } set { selectionCommand = value; } } public ViewModel() { selectionCommand = new Command(onSelectionChanged); } private void onSelectionChanged() { }
Screenshot
You can download a working sample for this KB here.