Category / Section
How to sort SfDataGrid columns using a bindable picker in MVVM approach?
1 min read
The SfDataGrid columns can be sorted using a bindable picker in MVVM approach, by using the “EventToCommand” behavior.
In the code below, the “GridLoaded” event of the SfDataGrid and “SelectedIndexChanged” event of the picker is passed as commands.
<Grid> <Grid.RowDefinitions> <RowDefinition Height="500" /> <RowDefinition Height="200" /> </Grid.RowDefinitions> <sfgrid:SfDataGrid x:Name="dataGrid" Grid.Row="0" AutoGenerateColumns="False" ColumnSizer="Star" ItemsSource="{Binding OrdersInfo}"> <b:Interaction.Behaviors> <b:BehaviorCollection> <b:EventToCommand Command="{Binding DataGridCommand}" CommandParameter="{x:Reference Name=dataGrid}" EventName="GridLoaded" /> </b:BehaviorCollection> </b:Interaction.Behaviors> <sfgrid:SfDataGrid.Columns> <sfgrid:GridTextColumn HeaderText="Order ID" MappingName="OrderID" /> <sfgrid:GridTextColumn HeaderText="Customer ID" MappingName="CustomerID" /> <sfgrid:GridTextColumn HeaderText="Freight" MappingName="Freight" /> <sfgrid:GridTextColumn HeaderText="Country" MappingName="Country" /> </sfgrid:SfDataGrid.Columns> </sfgrid:SfDataGrid> <Picker x:Name="ColumnPicker" Title="ColumnPicker" Grid.Row="1" BackgroundColor="Gray" HorizontalOptions="FillAndExpand" TextColor="Black"> <b:Interaction.Behaviors> <b:BehaviorCollection> <b:EventToCommand Command="{Binding PickerCommand}" CommandParameter="{x:Reference Name=ColumnPicker}" EventName="SelectedIndexChanged" /> </b:BehaviorCollection> </b:Interaction.Behaviors> <Picker.Items> <x:String>OrderID</x:String> <x:String>CustomerID</x:String> <x:String>Freight</x:String> <x:String>Country</x:String> </Picker.Items> </Picker> </Grid>
The following code gives the implementation of the commands.
public ViewModel() { _dataGridCommand = new Command(GridLoaded); _pickerCommand = new Command(SelectedItemChanged); SetRowstoGenerate(50); } #region private variables private SfDataGrid dataGrid; private Command _pickerCommand; private Command _dataGridCommand; #endregion #region Public Properties public Command PickerCommand { get { return _pickerCommand; } set { _pickerCommand = value; this.RaisePropertyChanged("PickerCommand"); } } public Command DataGridCommand { get { return _dataGridCommand; } set { _dataGridCommand = value; RaisePropertyChanged("DataGridCommand"); } } #endregion #region Command methods //Here we get the SfDataGrid private void GridLoaded(object obj) { dataGrid = obj as SfDataGrid; } //Here we get the Picker private void SelectedItemChanged(object obj) { var picker = obj as Picker; dataGrid.SortColumnDescriptions.Clear(); dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = dataGrid.Columns[picker.SelectedIndex].MappingName, SortDirection = Syncfusion.Data.ListSortDirection.Descending }); } #endregion
Screenshot:
Sample Link:
How to sort SfDataGrid columns using a bindable picker in MVVM approach