Articles in this section
Category / Section

How to pass selected row's Xamarin.Forms DataGrid to a command?

5 mins read

SfDataGrid provides two events for selection: SelectionChanging and SelectionChanged. It provides the added items and the removed items as arguments in it. You can pass the selected row info to a command in the ViewModel by using the Xamarin.Forms Behaviors.

Refer the below code example in which a custom behavior for passing the selected row information to ViewModel is defined.

<?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:syncfusion="clr-namespace:Syncfusion.SfDataGrid.XForms;assembly=Syncfusion.SfDataGrid.XForms"

             xmlns:local="clr-namespace:SelectionSample"

             x:Class="SelectionSample.MainPage">

 

  <ContentPage.BindingContext>

    <local:ViewModel x:Name="viewModel" />

  </ContentPage.BindingContext>

 

  <ContentPage.Resources>

    <ResourceDictionary>

      <local:CustomConverter x:Key="gridSelectionChangedEventArgs" />

    </ResourceDictionary>

  </ContentPage.Resources>

 

  <syncfusion:SfDataGrid x:Name="dataGrid"

                     ColumnSizer="Star"

                     SelectionMode="Single"

                     ItemsSource="{Binding OrderInfo}">

    <syncfusion:SfDataGrid.Behaviors>

      <local:CustomBehavior Command="{Binding SelectionCommand}"

                            Converter="{StaticResource gridSelectionChangedEventArgs}" />

    </syncfusion:SfDataGrid.Behaviors>

  </syncfusion:SfDataGrid>

</ContentPage>s


 

The below code illustrates the command and the call back implementation to get the selected row information.

public class ViewModel
    {
        private ICommand selectionCommand;
        public ICommand SelectionCommand
        {
            get { return selectionCommand; }
            set { selectionCommand = value; }
        }
        public ViewModel()
        {
            selectionCommand = new Command<GridSelectionChangedEventArgs>(OnSelectionChanged);
            OrderInfoRepository orderInfoRepository = new OrderInfoRepository();
            orderInfo = orderInfoRepository.GetOrderDetails(30);
        }
        private ObservableCollection<OrderInfo> orderInfo;
 
        public ObservableCollection<OrderInfo> OrderInfo
        {
            get { return orderInfo; }
            set { this.orderInfo = value; }
        }
        internal void GenerateItemsSource(int count)
        {
            OrderInfoRepository order = new OrderInfoRepository();
            orderInfo = order.GetOrderDetails(count);
        }
        private void OnSelectionChanged(GridSelectionChangedEventArgs e)
        {
            var SelectedItem = e.AddedItems;
        }
    }

 

 

The below code illustrates the behavior class implementation for the SfDataGrid.

public class CustomBehavior : Behavior<SfDataGrid>
    {
        public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(CustomBehavior), null);
        public static readonly BindableProperty InputConverterProperty = BindableProperty.Create("Converter", typeof(IValueConverter), typeof(CustomBehavior), null);
 
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
 
        public IValueConverter Converter
        {
            get { return (IValueConverter)GetValue(InputConverterProperty); }
            set { SetValue(InputConverterProperty, value); }
        }
 
        public SfDataGrid AssociatedObject { get; private set; }
 
 
        protected override void OnAttachedTo(SfDataGrid bindable)
        {
            base.OnAttachedTo(bindable);
            AssociatedObject = bindable;
            bindable.BindingContextChanged += OnBindingContextChanged;
            bindable.SelectionChanged += bindable_SelectionChanged;
        }
 
        void bindable_SelectionChanged(object sender, GridSelectionChangedEventArgs e)
        {
            if (Command == null)
            {
                return;
            }
 
            object parameter = Converter.Convert(e, typeof(object), null, null);
            var temp = (parameter as GridSelectionChangedEventArgs).AddedItems;
 
            if (Command.CanExecute(parameter))
            {
                Command.Execute(parameter);
            }
        }
 
 
        protected override void OnDetachingFrom(SfDataGrid bindable)
        {
            base.OnDetachingFrom(bindable);
            bindable.BindingContextChanged -= OnBindingContextChanged;
            bindable.SelectionChanged -= bindable_SelectionChanged;
            AssociatedObject = null;
        }
        void OnBindingContextChanged(object sender, EventArgs e)
        {
            OnBindingContextChanged();
        }
 
        protected override void OnBindingContextChanged()
        {
            base.OnBindingContextChanged();
            BindingContext = AssociatedObject.BindingContext;
        }
    }

 

Screenshot:

 

Sample Link:

How to pass selected row info to a command?


Conclusion

I hope you enjoyed learning about how to pass selected row's Xamarin.Forms DataGrid to a command.

You can refer to our Xamarin.Forms DataGrid feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied