相关文章推荐

Getting Started with WPF DataGrid (SfDataGrid)

18 Jun 2023 16 minutes to read

This section provides a quick overview for working with the WPF DataGrid (SfDataGrid) for WPF. Walk through the entire process of creating a real world of this control.

To get start quickly with WPF DataGrid, you can check on this video:

Creating simple application with SfDataGrid

In this walk through, you will create WPF application that contains SfDataGrid control.

  • Creating project
  • Adding control via Designer
  • Adding control manually in XAML
  • Adding control manually in C#
  • Creating Data Model for application
  • Binding to Data
  • Defining Columns
  • Selection
  • Sorting, Grouping, and Filtering
  • Editing
  • Creating the project

    Create new WPF Project in Visual Studio to display SfDataGrid with data objects.

    Adding control via Designer

    SfDataGrid control can be added to the application by dragging it from Toolbox and dropping it in Designer view. The required assembly references will be added automatically.

    Adding control manually in XAML

    In order to add control manually in XAML, do the below steps,

  • Add the below required assembly references to the project,
  • Syncfusion.Data.WPF
  • Syncfusion.SfGrid.WPF
  • Syncfusion.Shared.WPF
  • Import Syncfusion WPF schema http://schemas.syncfusion.com/wpf or SfDataGrid control namespace Syncfusion.UI.Xaml.Grid in XAML page.
  • Declare SfDataGrid control in XAML page.

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:syncfusion="http://schemas.syncfusion.com/wpf" 
            x:Class="WpfApplication1.MainWindow"
            Title="MainWindow" Height="350" Width="525">
            <syncfusion:SfDataGrid  x:Name="dataGrid"/>
        </Grid>
    </Window>
    InitializeComponent (); SfDataGrid dataGrid = new SfDataGrid (); Root_Grid . Children . Add ( dataGrid ); public OrderInfo ( int orderId , string customerName , string country , string customerId , string shipCity ) this . OrderID = orderId ; this . CustomerName = customerName ; this . Country = country ; this . CustomerID = customerId ; this . ShipCity = shipCity ; private ObservableCollection < OrderInfo > _orders ; public ObservableCollection < OrderInfo > Orders get { return _orders ; } set { _orders = value ; } public ViewModel () _orders = new ObservableCollection < OrderInfo >(); this . GenerateOrders (); private void GenerateOrders () _orders . Add ( new OrderInfo ( 1001 , "Maria Anders" , "Germany" , "ALFKI" , "Berlin" )); _orders . Add ( new OrderInfo ( 1002 , "Ana Trujilo" , "Mexico" , "ANATR" , "Mexico D.F." )); _orders . Add ( new OrderInfo ( 1003 , "Antonio Moreno" , "Mexico" , "ANTON" , "Mexico D.F." )); _orders . Add ( new OrderInfo ( 1004 , "Thomas Hardy" , "UK" , "AROUT" , "London" )); _orders . Add ( new OrderInfo ( 1005 , "Christina Berglund" , "Sweden" , "BERGS" , "Lula" )); _orders . Add ( new OrderInfo ( 1006 , "Hanna Moos" , "Germany" , "BLAUS" , "Mannheim" )); _orders . Add ( new OrderInfo ( 1007 , "Frederique Citeaux" , "France" , "BLONP" , "Strasbourg" )); _orders . Add ( new OrderInfo ( 1008 , "Martin Sommer" , "Spain" , "BOLID" , "Madrid" )); _orders . Add ( new OrderInfo ( 1009 , "Laurence Lebihan" , "France" , "BONAP" , "Marseille" )); _orders . Add ( new OrderInfo ( 1010 , "Elizabeth Lincoln" , "Canada" , "BOTTM" , "Tsawassen" ));

    Binding to Data

    To bind the SfDataGrid to data, set the SfDataGrid.ItemsSource property to an IEnumerable implementation. Each row in SfDataGrid is bound to an object in data source and each column in SfDataGrid bound to a property in data object.

    Bind the collection created in previous step to SfDataGrid.ItemsSource property in XAML by setting ViewModel as DataContext .

    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:syncfusion="http://schemas.syncfusion.com/wpf" 
            x:Class="WpfApplication1.MainWindow"
            xmlns:local="clr-namespace:WpfApplication1"
            Title="MainWindow" Height="350" Width="525">
        <Window.DataContext>
            <local:ViewModel/>
        </Window.DataContext>
        <Grid x:Name="Root_Grid">
            <syncfusion:SfDataGrid x:Name="dataGrid"  ItemsSource="{Binding Orders}" />
        </Grid>
    </Window>
    ViewModel viewModel = new ViewModel();
    dataGrid.ItemsSource = viewModel.Orders;

    Defining Columns

    By default, the SfDataGrid control generates the columns automatically when value assigned to SfDataGrid.ItemsSource property. The type of the column generated depends on the type of data in the column and the attribute of the property the column bound with.

    The following table lists the column types and its constraints for auto column generation.

    When columns are auto-generated, you can handle the SfDataGrid.AutoGeneratingColumn event to customize or cancel the columns before they are added to the SfDataGrid.

    You can prevent the automatic column generation by setting SfDataGrid.AutoGenerateColumns property is false , you have to define the columns to be displayed as below,

    <syncfusion:SfDataGrid x:Name="dataGrid"  
                           ItemsSource="{Binding Orders}" 
                           AutoGenerateColumns="False">
        <syncfusion:SfDataGrid.Columns>
            <syncfusion:GridTextColumn MappingName="CustomerID"/>
            <syncfusion:GridTextColumn MappingName="CustomerName"/>
        </syncfusion:SfDataGrid.Columns>
    </syncfusion:SfDataGrid>
    SfDataGrid dataGrid = new SfDataGrid();
    dataGrid.AutoGenerateColumns = false;
    dataGrid.Columns.Add(new GridTextColumn() { MappingName = "CustomerID" });
    dataGrid.Columns.Add(new GridTextColumn() { MappingName = "CustomerName" });

    Selection

    By default, the entire row is selected when a user clicks a cell in a SfDataGrid. You can set the SfDataGrid.SelectionMode property to specify whether a user can select single row or cell, or multiple rows or cells. Set the SfDataGrid.SelectionUnit property to specify whether rows can be selected, or cells can selected.

    When SelectionUnit is Row , you can get information about the rows that are selected using SfDataGrid.SelectedItem and SfDataGrid.SelectedItems properties.

    When SfDataGrid.SelectionUnit is Cell , you can get information about the cells that are selected by calling SfDataGrid.GetSelectedCells method.

    You can handle the selection operations with the help of SfDataGrid.SelectionChanging and SfDataGrid.SelectionChanged events of SfDataGrid.

    Sorting, Grouping, and Filtering

    Sorting

    By default, you can sort columns in a SfDataGrid by clicking the column header. You can configure the sorting by setting SfDataGrid.SortColumnDescriptions property as below,

    <syncfusion:SfDataGrid x:Name="dataGrid"  
                           ItemsSource="{Binding Orders}" >
        <syncfusion:SfDataGrid.SortColumnDescriptions>
            <syncfusion:SortColumnDescription ColumnName="CustomerName"/>
        </syncfusion:SfDataGrid.SortColumnDescriptions>
    </syncfusion:SfDataGrid>
    this.dataGrid.SortColumnsChanging += dataGrid_SortColumnsChanging;
    void dataGrid_SortColumnsChanging(object sender, GridSortColumnsChangingEventArgs e)
        if (e.AddedItems[0].ColumnName == "CustomerName")
        e.Cancel = true;
    
    <syncfusion:SfDataGrid x:Name="dataGrid"  
                           ItemsSource="{Binding Orders}" >
        <syncfusion:SfDataGrid.GroupColumnDescriptions>
            <syncfusion:GroupColumnDescription ColumnName="CustomerName"/>
        </syncfusion:SfDataGrid.GroupColumnDescriptions>
    </syncfusion:SfDataGrid>

    Filtering

    Filtering can be enabled by setting SfDataGrid.AllowFiltering property to true , where you can open advanced filter UI by clicking the Filter icon in column header and filter the SfDataGrid. You can customize the filtering operations by handling SfDataGrid.FilterChanging and SfDataGrid.FilterChanged events.

    Editing

    Editing can be enabled by setting SfDataGrid.AllowEditing property to true . Set SfDataGrid.AllowDeleting property to specify whether user can delete rows by pressing Delete key.

    Set SfDataGrid.AddNewRowPosition property to enable additional row either Top or Bottom of SfDataGrid, where user can enter new items into the blank row. Adding new row adds an item to the SfDataGrid.ItemsSource.

    You can customize the editing operations by handling SfDataGrid.CurrentCellBeginEdit and SfDataGrid.CurrentCellEndEdit events.

    Theme

    SfDataGrid supports various built-in themes. Refer to the below links to apply themes for the SfDataGrid,

    Apply theme using SfSkinManager

    Create a custom theme using ThemeStudio

     
    推荐文章