Data Binding in WPF DataGrid (SfDataGrid)
22 Feb 202424 minutes to read
WPF DataGrid (SfDataGrid) control is designed to display the bounded data in a tabular format. The data binding can be achieved by assigning the data sources to SfDataGrid.ItemsSource property.
<syncfusion:SfDataGrid x:Name="dataGrid"
AutoGenerateColumns="True"
ItemsSource="{Binding Orders}" />
If the data source implements INotifyCollectionChanged interface, then SfDataGrid control will automatically refresh the UI when item is added, removed or while list cleared.
When you add, remove item in ObservableCollection, SfDataGrid automatically refresh the UI as ObservableCollection
implements INotifyCollectionChanged
. But when you do the same in List, SfDataGrid will not refresh the UI automatically.
Binding with IEnumerable
WPF DataGrid (SfDataGrid) control supports to bind any collection that implements the IEnumerable interface. All the data operations such as sorting, grouping, filtering, summaries are supported when you are binding collection derived from IEnumerable.
Binding with DataTable
WPF DataGrid (SfDataGrid) control supports to bind the DataTable. SfDataGrid control automatically refresh the UI when you are binding DataTable as ItemsSource when rows are added, removed or cleared.
Below are the limitations when binding DataTable as ItemsSource to SfDataGrid.
- GridUnboundColumn.Expression is not supported. You can achieve the expression support when binding DataTable using DataColumn of DataTable by setting DataColumn.Expression property.
-
AddNewRow
is not support when filtering is enabled. - Advanced Filtering does not support Case Sensitive filtering.
- SfDataGrid.View.Filter is not supported.
- Custom sorting is not supported.
- Filtering with TimeSpan values is not supported.
- SfDataGrid.LiveDataUpdateMode is not supported.
- Filtering with sub second components in
DateTime
values is not supported.
Apply DataView.RowFilter on initial loading
When DataTable is bounded as SfDataGrid.ItemsSource
, the DataView.RowFilter will not be applied to the data on initial loading by default. The DataView.RowFilter
can be applied to the data on initial loading by enabling CanUseViewFilter property.
Binding with dynamic data object
WPF DataGrid (SfDataGrid) control supports to bind dynamic data object. Below are the limitations when you are binding dynamic data object,
- SfDataGrid doesn’t support LiveDataUpdateMode -
AllowDataShaping
andAllowSummaryUpdate
. - In WinRT, UI won’t get refreshed when you are changing the property value. This is limitation in WinRT platform.
All the data operations (sorting, grouping, filtering and etc.) are supported when you are binding dynamic data object. If the data operations are not working as expected, set SfDataGrid.IsDynamicItemsSource property astrue
.
Binding Complex properties
SfDataGrid control provides support to bind complex property to its columns. To bind the complex property to GridColumn, set the complex property path to MappingName.
<syncfusion:SfDataGrid AutoGenerateColumns="False" ItemsSource="{Binding Orders}">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="OrderID" />
<syncfusion:GridTextColumn MappingName="Customer.CustomerID" />
<syncfusion:GridTextColumn MappingName="ShipCity" />
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
All the data operations (sorting, grouping, filtering and etc.) are supported when you are binding complex property. If the data operations are not working as expected, set GridColumn.UseBindingValue as true
to make it work.
Limitations when binding complex property
- SfDataGrid doesn’t support LiveDataUpdateMode -
AllowDataShaping
andAllowSummaryUpdate
.
Binding Indexer properties
SfDataGrid control provides support to bind an indexer property to its columns. To bind an indexer property to GridColumn, set the indexer property path to MappingName.
<syncfusion:SfDataGrid x:Name="dataGrid" ItemsSource="{Binding Students}" AutoGenerateColumns="False">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="RollNo"/>
<syncfusion:GridTextColumn MappingName="Name"/>
<syncfusion:GridTextColumn MappingName="Marks[0]"/>
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
this.dataGrid.Columns.Add(new GridTextColumn() {MappingName="Marks[0]"});
All the data operations (sorting, grouping, filtering and etc.) are supported when you are binding indexer property. If the data operations are not working as expected, set GridColumn.UseBindingValue as true
to make it work.
Limitations when binding indexer property
- SfDataGrid doesn’t support LiveDataUpdateMode -
AllowDataShaping
andAllowSummaryUpdate
. - SfDataGrid doesn’t support AutoGenerateColumns.
Defining source data type
Based on type of data item bound to SfDataGrid, the data operations and column auto generation are carried out. You can specify the type of underlying data item explicitly for doing data operation by setting SfDataGrid.SourceType property.
<syncfusion:SfDataGrid x:Name="dataGrid" ItemsSource="{Binding Orders}" SourceType="{x:Type local:OrderInfo}"/>
dataGrid.SourceType = typeof(OrderInfo);
For example, when you set SourceType property, the columns are generated based on members of SourceType regardless of data items actual type. When your ItemsSource
have different types derived from same type, you can set SourceType as base type for all different types.
Events
ItemsSourceChanged
SfDataGrid.ItemsSourceChanged event occurs when the data source is changed by using ItemsSource property.
This event receives two arguments namely sender
that handles SfDataGrid
and GridItemsSourceChangedEventArgs as objects.
The GridItemsSourceChangedEventArgs object contains the following properties:
- OldItemsSource - Gets the value of old data source
- NewItemsSource - Get the value of new data source
View
WPF DataGrid has the View property of type ICollectionViewAdv interface that implements ICollectionView interface. View is responsible for maintain and manipulation data and other advanced operations like Sorting, Grouping, Filtering and etc.
When you bind Collection to ItemsSource
property of SfDataGrid, then View will be created and maintains the operations on Data such as Grouping, Filtering, Sorting, Insert, Delete, and Modification.
Following are some important properties that can be used for various purposes.
NOTE
DataGrid creates different types of views derived from
ICollectionViewAdv
interface based on ItemsSource.
Property | Type | Description |
---|---|---|
Records | IRecordsList | Maintains the Records that are displayed in View when DataGrid is not Grouped. |
TopLevelGroup | TopLevelGroup | Maintains the Group information when DataGrid is Grouped. |
TopLevelGroup.DisplayElements | GroupDisplayElements | Maintains the Records and Group information that are displayed in View when DataGrid is Grouped. |
Filter | Predicate<object> | Get or sets the method that determines the data is suitable to be displayed in View. |
FilterPredicates | ObservableCollection<IFilterDefinition> | Maintains the FilterPredicates that are created while filtering using Filtering UI. |
Groups | ReadOnlyObservableCollection<object> | Maintains the top-level group information. It returns null value when there are no groups. |
GroupDescriptions | ObservableCollection<GroupDescription> | Maintains the GroupDescription collection information. It describes how the items in the collection are grouped in the view. |
SortDescriptions | SortDescriptionCollection | Maintains the SortDescription collection information. It describes how the items in the collection are sort in the view. |
SourceCollection | IEnumerable | Maintains the underlying source collection. |
TableSummaryRows | ObservableCollection<ISummaryRow> | Maintains the TableSummaryRows collection information. To know more about TableSummaries |
SummaryRows | ObservableCollection<ISummaryRow> | Maintains the SummaryRows collection information. To know more about summaries |
CaptionSummaryRows | ISummaryRow | Maintains the CaptionSummaryRow information.To know more about CaptionSummaries |
The following events are associated with View.
RecordPropertyChanged
RecordPropertyChanged event is raised when the DataModel property value is changed, if the DataModel implements the INotifyPropertyChanged interface. The event receives with two arguments namely sender that handles the DataModel and PropertyChangedEventArgs as object.
PropertyChangedEventArgs
has below property,
PropertyName – It denotes the PropertyName of the changed value.
CollectionChanged
CollectionChanged event is raised whenever that is some change in Records / DisplayElements collection. The event receives two arguments namely sender that handles View object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs
has below properties,
Action - It contains the current action. (i.e.) Add, Remove, Move, Replace, Reset.
NewItems - It contains the list of new items involved in the change.
OldItems - It contains the list of old items affected by the Action.
NewStartingIndex - It contains the index at which the change occurred.
OldStartingIndex-It contains the index at which the Action occurred.
SourceCollectionChanged
SourceCollectionChanged event is raised when you make changes in SourceCollection for example add or remove the collection. The event receives two arguments namely sender that handles GridQueryableCollectionViewWrapper object and NotifyCollectionChangedEventArgs as object.
NotifyCollectionChangedEventArgs
has below properties,
Action - It contains the current action. (i.e.) Add, Remove, Move, Replace, Reset.
NewItems - It contains the list of new items involved in the change.
OldItems - It contains the list of old items affected by the Action.
NewStartingIndex - It contains the index at which the change occurred.
OldStartingIndex - It contains the index at which the Action occurred.
The following is the methods that are associated with View which can be used to defer refresh the view.
Method Name | Description |
---|---|
DeferRefresh | Enter the defer cycle so that you can perform all data operations in view and update once. |
BeginInit & EndInit | When BeginInit method is called it suspends all the updates until EndInit method is called. You can perform all the updation with in these methods and update the view at once. |
NOTE
View has properties that already defined in SfDataGrid. It recommended setting those properties via SfDataGrid.
Binding data from WCF service
In this walkthrough, you will learn about how to create a WCF service and load it to SfDataGrid control.
Below are the topics,
- Creating the WCF data service
- Creating the WPF Client Application
- Loading data from WCF Service
Create the WCF data service
To create the WCF data service, follow the steps mentioned in the below MSDN link or the follow below steps,
You can skip the below steps and directly add service reference to the client application, if you are having already running service.
Create an ASP.NET Web Application
To create an ASP.NET Web Application, follow the below steps,
- In NewProject dialog box, select the Web template under Visual C# and then select ASP.NET Web Application.
-
Name the project file as WCF_Binding and then click OK to create project.
Define data model using ADO.NET Entity Data Model
Follow the below steps to define ADO.NET Entity Data Model in the web project created in the previous step,
- Right-click on your web project, select Add option and then click New Item.
- In the Add New Item wizard, select ADO.NET Entity Data Model under Data Template.
- Name the data model as “Northwind” and click Add button.
-
In the Entity Data Model Wizard, select EF Designer from Database, and then click Next.
-
Choose Your Data Connection page appears and select Northwind database available in the drop-down list (OR) select the New Connection button to configure a new data connection. For more information, you can refer: How to: Create Connections to SQL Server Databases.
- Click Next button and the Choose Your Database Objects and settings page appears.
-
Expand Tables node and select Order_Details table.
- Now select Finish button to add the entity model for “Northwind.edmx” file to your web project.
Add the WCF Data Service to web application
To add the WCF Data Service to your web project created in first step,
- Right-click on your web project, select Add option and then click New Item.
- In Add New Item Wizard, Select WCF Data Service 5.6 under Web Template.
-
In Name text box enter WcfDataService1.svc and then click Add button.
-
Once service is added and configure the read and write access to resources in InitializeService function of DataService.
- On the menu bar, select Debug->Start without Debugging to execute the service. A browser window opens and the XML schema for the service is displayed. You can also get the localhost address for the service here.
Creating the WPF Client Application
To create the WPF client application, add new WPF project in the same solution and name the project as NorthwindEditor. After creating the WPF application, you can add the service created in previous step to your WPF project.
To add service reference to client application,
- Right-click on your WPF project and select Add Service Reference option to add the service created in previous step.
- Add Service Reference wizard appears, then select Discover button which displays the list of available services in Services panel.
-
Select WcfDataService1.svc and click OK option to add the service reference to your WPF project.
Loading data from WCF service
To load the data from WCF service to SfDataGrid,
- Add SfDataGrid control and the required assemblies in your WPF application.
- Wire the SfDataGrid.Loaded event and set the northwindEntities.Order_Details table to
SfDataGrid.ItemsSource
. - Replace local host address as URI of your service. You can get the local host address from the shortcut menu of the “WcfDataService1.svc” file in Solution Explorer and select View in Browser. Internet Explorer opens and the XML schema for the service is displayed.
- Copy the localhost address and replace it in your service URI.
-
Set the WPF application as StartUp project.
this.dataGrid.Loaded += dataGrid_Loaded; void dataGrid_Loaded(object sender, RoutedEventArgs e) { NORTHWNDEntities northwindEntities = new NORTHWNDEntities(new Uri("http://localhost:58378/WcfDataService1.svc/")); this.dataGrid.ItemsSource = northwindEntities.Order_Details; }
Now, run the application and you can see the SfDataGrid control loaded with data from WCF service.
Binding data from ADO.NET Entity Framework
SfDataGrid control supports to bind data from ADO.NET Entity Framework. In this walk-through, you will learn about binding data from ADO.NET Entity Framework and save back the changes to the database. You can download the entire source code of this demo from here.
To load the data from ADO.NET Entity Framework, you can refer the steps mentioned in below follow the below steps,
- Creating WPF client Application.
- Defining Data Model using Entity Framework 4.0
- Loading data from Entity Framework.
References :
https://learn.microsoft.com/en-us/previous-versions/dd465159(v=vs.120)
https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ee340709(v=vs.100)
https://learn.microsoft.com/en-us/ef/ef6/modeling/designer/workflows/database-first
Creating WPF client Application
To load data from Entity Framework, create a new WPF Application and add the SfDataGrid control to your application.
Defining Data Model using Entity Framework 4.0
To create Data Model using Entity Framework in WPF application created in the previous step,
- Right-click your WPF project, select Add option and then click New Item.
- The Add New Item wizard appears, select “ADO.NET Entity Data Model “ from the Data node.
-
Name the file as Model1.edmx and then select Add button.
-
The Entity Data Model wizard appears.
-
In the Choose Model Contents, select Generate from database option and then click Next.
-
In the Choose Your Data Connection, select Northwind database from the drop-down list for data connection. To configure/modify connection, you can refer: How to: Create Connections to SQL Server Databases.
- Enable the Save entity connection settings in App.config as check box and then click Next.
-
In the Choose Your Database Objects and Settings, expand the Tables node and select the Order_Details table.
- Click Finish button to add the EntityBindingFramework.edmx file to your application. The Entity diagram for the Order_detail table is opened.
Loading data from Entity Framework data service
To access data from the database created in previous step, create a ViewModel class with OrderDetails property and the OrderDetails is initialized by accessing the Order_Details table from the database.
public class ViewModel
{
private List<Order_Detail> orderDetails;
public List<Order_Detail> OrderDetails
{
get { return orderDetails; }
set { orderDetails = value; }
}
public ViewModel()
{
NORTHWNDEntities northWind = new NORTHWNDEntities();
OrderDetails = (List<Order_Detail>)(from data in northWind.Order_Details
select data).ToList();
}
}
To populate the SfDataGrid using Entity Framework, bind the collection created in previous step to SfDataGrid.ItemsSource property and set the DataContext
as ViewModel.
<syncfusion:SfDataGrid x:Name="dataGrid"
AllowEditing="True"
AutoGenerateColumns="True"
ItemsSource="{Binding OrderDetails}"/>
Now, run the application and you can see the following screenshot shows the SfDataGrid control populated with data from Entity Framework data service.
Save back to Database
You can save the row or cell level changes back to the data source by handling SfDataGrid.RowValidated, SfDataGrid.CurrentCellValidated or SfDataGrid.CurrentCellValueChanged events.
The below code example will save back the changed value of row to data base.
NORTHWNDEntities northWind;
public MainWindow()
{
InitializeComponent();
northWind = new NORTHWNDEntities();
this.dataGrid.RowValidated += dataGrid_RowValidated;
}
void dataGrid_RowValidated(object sender, Syncfusion.UI.Xaml.Grid.RowValidatedEventArgs args)
{
Order_Detail newRecord = args.RowData as Order_Detail;
Order_Detail order = northWind.Order_Details.First(i => i.OrderID == newRecord.OrderID);
order.OrderID = newRecord.OrderID;
order.ProductID = newRecord.ProductID;
order.Quantity = newRecord.Quantity;
order.UnitPrice = newRecord.UnitPrice;
order.Discount = newRecord.Discount;
northWind.Entry(order).State = EntityState.Modified;
northWind.SaveChanges();
}
Binding data from LINQ to SQL
SfDataGrid control supports to bind data from LINQ to SQL .In this walkthrough, you will learn about binding data from LINQ to SQL and save back the changes to the Database.
- Creating WPF Application
- Adding data model using LINQ to SQL classes
- Loading data from LINQ to SQL classes
- Binding data to SfDataGrid
References :
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/data-binding
Creating WPF Client Application
To add LINQ to SQL, create a new WPF application and add the SfDataGrid control in your application.
Adding data model using LINQ to SQL
To create data model using LINQ to SQL in WPF project follow the below steps.
- Right-click on your WPF project, select Add option and then click New Item.
- The Add New Item wizard appears, select LINQ to SQL Classes from the Visual C#.
-
Name the file as Northwind and then select Add option to add the Northwind.dbml in your project.
-
Once the Northwind.dbml is added in your project, then the design view is opened.
- You can add new Database connection by clicking add icon button in Server Explorer.
-
The Add Connection wizard appeared with the default data source as Microsoft SQL Server Database File (SqlClient).
- Click Change to open the Change Data Source dialog box and select the type of data source that you have owned.
- In the Server name option, click the Refresh button to select the server from the drop down list.
-
Enable select or enter a database name radio button to select database from the drop down list under the Connect to a database option.
- Click Test Connection to check whether the connection with your database is succeeded or not.
-
Once the connection is succeeded, click OK button to add database in your server explorer.
- Drag Shippers table in to design view of Northwind.dbml. The Entity model diagram for Shippers table is generated once it is dropped in to design view.
Loading data from LINQ to SQL classes
To load the database created in previous step in to SfDataGrid, create a ViewModel class with Shippers property and it is initialized with Shippers table in Northwind database.
public class ViewModel
{
private List<Shipper> shippers;
public List<Shipper> Shippers
{
get { return shippers; }
set { shippers = value; }
}
public ViewModel()
{
NorthwindDataContext northWind = new NorthwindDataContext();
shippers = (from data in northWind.Shippers
select data).ToList();
}
}
NOTE
NorthwindDataContext is from
Northwind.Designer.cs
file (it is from the file that is added with LINQ to SQL). Shippers are selected table from Database.
Binding data to SfDataGrid
To bind data from LINQ to SQL classes, assign the Shippers collection created in the previous step, to SfDataGrid.ItemsSource property and set the DataContext
as ViewModel.
this.dataGrid.ItemsSource = (this.dataGrid.DataContext as ViewModel).Shippers;
Now, run the application and you can see the following screenshot shows the SfDataGrid control loaded with Shippers data.
Save back to Database
You can save the row or cell level changes back to the data source by handling SfDataGrid.RowValidated, SfDataGrid.CurrentCellValidated or SfDataGrid.CurrentCellValueChanged events.
The below code example will save back the changed value of row to database.
this.dataGrid.RowValidated += dataGrid_RowValidated;
void dataGrid_RowValidated(object sender, Syncfusion.UI.Xaml.Grid.RowValidatedEventArgs args)
{
NorthwindDataContext northWind = new NorthwindDataContext();
Shipper newRecord = args.RowData as Shipper;
Shipper shipper = (from data in northWind.Shippers
where data.ShipperID == newRecord.ShipperID
select data).First() as Shipper;
shipper.CompanyName = newRecord.CompanyName;
shipper.Phone = newRecord.Phone;
northWind.SubmitChanges();
}
Binding data from ADO.NET
SfDataGrid control supports to load the data using ADO.NET. In this walk-through, you will learn about binding data from ADO.NET service and save back the changes to the database.
- Creating WPF application
- Connecting database to WPF application
- Loading data using ADO.NET
Creating WPF Application
To display the data from the ADO.NET data service, create a new WPF Application.
Connecting WPF application to Databases
To connect SQL database to your WPF application, refer the below MSDN link or follow the below steps,
- In the Tools menu, select the Connect to Database.
-
The Add Connection wizard appeared with the default data source as Microsoft SQL Server Database File (SqlClient).
-
Click Change to open the Change Data Source dialog box and select the type of data source that you have owned.
- In the Server name option, click the Refresh button to select the server from the drop down list.
- Enable select or enter a database name radio button to select your database from the drop down list under the Connect to a database option.
- Click Test Connection to check whether the database connection is succeeded or not.
-
Once the connection is succeeded, click OK button to add database in your server explorer.
- To get connection string for the database, right-click on your database and then click properties option.
Loading data from ADO.NET
To access the data from data source using ADO.NET, follow the below steps.
- Create a user interface with SfDataGrid control and add the required assemblies to your WPF application.
- Create a connection through any of the .NET Framework data provider based on the type of data source that you have owned.
-
Set the ItemsSource as Shippers table from data set. For more information refer here.
public partial class MainWindow : Window { DataSet ds = new DataSet(); SqlConnection connectionString = new SqlConnection("Data Source=SYNCLAPN2712;Initial Catalog=NORTHWND.MDF;Integrated Security=True"); SqlDataAdapter adapter = null; public MainWindow() { InitializeComponent(); BindData(); } private void BindData() { connectionString.Open(); adapter = new SqlDataAdapter("Select * from Shippers ", connectionString); adapter.Fill(ds, "Shippers"); dataGrid.ItemsSource = ds.Tables["Shippers"]; } }
Now, run the application and you can see the following screenshot displays the SfDataGrid loaded the data using ADO.NET.
Save back to Database
You can save the row or cell level changes back to the data source by handling SfDataGrid.RowValidated, SfDataGrid.CurrentCellValidated or SfDataGrid.CurrentCellValueChanged events.
The below code example will save back the changed value of row to database.
You can refer the below MSDN link for more information.
this.dataGrid.RowValidated += dataGrid_RowValidated;
void dataGrid_RowValidated(object sender, Syncfusion.UI.Xaml.Grid.RowValidatedEventArgs args)
{
adapter.UpdateCommand = new SqlCommand("UPDATE Shippers SET CompanyName = @CompanyName " + "," + "Phone = @Phone " +
"WHERE ShipperID = @ShipperID", connectionString);
adapter.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
adapter.UpdateCommand.Parameters.Add("@Phone", SqlDbType.NVarChar, 24, "Phone");
SqlParameter parameter = adapter.UpdateCommand.Parameters.Add("@ShipperID", SqlDbType.Int, 4);
parameter.SourceColumn = "ShipperID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable shippersTable = new DataTable();
shippersTable.Clear();
adapter.Fill(shippersTable);
DataRow shippersRow = shippersTable.Rows[args.RowIndex - 1];
shippersRow["CompanyName"] = (args.RowData as DataRowView).Row.ItemArray[1];
shippersRow["Phone"] = (args.RowData as DataRowView).Row.ItemArray[2];
adapter.Update(shippersTable);
}
Binding data from Microsoft Access
SfDataGrid control supports to bind data from Microsoft Access database .In this section, you will learn about how to bind the data from Microsoft Access database to SfDataGrid.
To load the data from Microsoft Access database,
- Create a new WPF project.
- Import the Microsoft Access database file to WPF project.
- You can connect the Microsoft Access Database through the
OleDbConnection
. - Create and open the connection.
- Use
OleDbDataAdapter
to load the data in toDataSet
. -
Access the Employee table from the DataSet and set the Employee collection as
ItemsSource
of SfDataGrid.this.dataGrid.Loaded+=dataGrid_Loaded; void dataGrid_Loaded(object sender, RoutedEventArgs e) { System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=EmployeeDatabase.accdb;Persist Security Info=True"); System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM Employee", con); DataSet ds = new DataSet(); con.Open(); myDataAdapter.Fill(ds, "Employee"); con.Close(); dataGrid.ItemsSource = ds.Tables["Employee"]; }
7.Now, run the application and you can see following screenshot shows the SfDataGrid control populated data from Microsoft Access database.
How To
Maintain scroll position when changing the ItemsSource for SfDataGrid
By default, the scrollbar position is not maintained and gets reset when changing the ItemsSource of the SfDataGrid. But, you can maintain the scrollbar position of the SfDataGrid by setting the SfDataGrid.CanMaintainScrollPosition value to true
.
<syncfusion:SfDataGrid x:Name="dataGrid"
CanMaintainScrollPosition="True"
ItemsSource="{Binding Orders}"/>
dataGrid.CanMaintainScrollPosition = true;