syncfusion-wpf-datagrid
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSyncfusion WPF DataGrid
Syncfusion WPF DataGrid
The Syncfusion WPF DataGrid (SfDataGrid) is a high-performance, feature-rich component for displaying and manipulating tabular data in Windows Presentation Foundation applications. It provides extensive functionality for data binding, column configuration, sorting, filtering, grouping, editing, and export capabilities.
Syncfusion WPF DataGrid(SfDataGrid)是一款高性能、功能丰富的组件,用于在Windows Presentation Foundation应用中显示和操作表格数据。它提供了数据绑定、列配置、排序、筛选、分组、编辑和导出等丰富功能。
When to Use This Skill
何时使用本组件
Use the Syncfusion WPF DataGrid when you need to:
- Display tabular data in Windows Presentation Foundation applications
- Handle large datasets efficiently with virtualization and performance optimization
- Enable data operations like sorting, filtering, and grouping
- Implement data editing with validation and custom editors
- Export data to Excel or PDF formats
- Create hierarchical views with master-detail relationships
- Calculate summaries for groups, tables, or captions
- Customize appearance with conditional styling and themes
- Support MVVM pattern with comprehensive data binding
- Configure columns with various types and auto-sizing strategies
在以下场景中使用Syncfusion WPF DataGrid:
- 在Windows Presentation Foundation应用中显示表格数据
- 通过虚拟化和性能优化高效处理大型数据集
- 启用排序、筛选和分组等数据操作
- 实现带验证和自定义编辑器的数据编辑功能
- 将数据导出为Excel或PDF格式
- 创建带主从关系的分层视图
- 计算分组、表格或标题的汇总信息
- 通过条件样式和主题自定义外观
- 通过全面的数据绑定支持MVVM模式
- 使用各种列类型和自动调整策略配置列
Component Overview
组件概述
The SfDataGrid component offers:
- Data Binding: Support for any IEnumerable source, DataTable, and MVVM patterns
- Column Types: 15+ built-in column types (Text, Numeric, DateTime, ComboBox, CheckBox, etc.)
- Data Operations: Advanced sorting, filtering, and grouping with custom logic support
- Editing: In-line editing with validation, custom editors, and add/delete operations
- Export: Export to Excel and PDF with customization options
- Summaries: Table, group, and caption summaries with built-in aggregates
- Master-Detail: Nested grid views for hierarchical data display
- Styling: Conditional styling, themes, and complete visual customization
- Performance: UI virtualization, on-demand loading, and optimized rendering
- Selection: Multiple selection modes (row, cell, extended) with programmatic control
SfDataGrid组件提供以下功能:
- 数据绑定:支持任何IEnumerable数据源、DataTable和MVVM模式
- 列类型:15+种内置列类型(文本、数值、日期时间、下拉框、复选框等)
- 数据操作:支持自定义逻辑的高级排序、筛选和分组
- 编辑功能:带验证、自定义编辑器和添加/删除操作的行内编辑
- 导出功能:可自定义的Excel和PDF导出
- 汇总功能:表格、分组和标题汇总,内置聚合函数
- 主从视图:用于分层数据显示的嵌套网格视图
- 样式定制:条件样式、主题和完全的视觉自定义
- 性能优化:UI虚拟化、按需加载和优化渲染
- 选择功能:多种选择模式(行、单元格、扩展选择),支持程序化控制
Documentation and Navigation Guide
文档与导航指南
Getting Started and Setup
入门与设置
📄 Read: references/getting-started.md
When to read:
- Setting up SfDataGrid for the first time in a WPF project
- Installing NuGet packages and adding assembly references
- Configuring basic grid with data binding
- Understanding namespace imports and XAML setup
- Implementing license registration
Covers:
- Installation via NuGet (Syncfusion.SfGrid.WPF)
- Assembly references and dependencies
- Basic XAML markup for SfDataGrid
- Data binding with ItemsSource
- Auto-generating columns
- License configuration
- Essential namespace imports
📄 阅读: references/getting-started.md
阅读时机:
- 首次在WPF项目中设置SfDataGrid
- 安装NuGet包并添加程序集引用
- 配置带数据绑定的基础网格
- 了解命名空间导入和XAML设置
- 实现许可证注册
涵盖内容:
- 通过NuGet安装(Syncfusion.SfGrid.WPF)
- 程序集引用和依赖项
- SfDataGrid的基础XAML标记
- 使用ItemsSource进行数据绑定
- 自动生成列
- 许可证配置
- 必要的命名空间导入
Columns and Configuration
列与配置
Column Types and Definition
列类型与定义
📄 Read: references/columns.md
When to read:
- Defining columns manually instead of auto-generation
- Using specific column types (GridTextColumn, GridNumericColumn, etc.)
- Configuring column properties (HeaderText, MappingName, Width)
- Managing column operations (add, remove, reorder)
- Enabling column resizing and drag-drop
- Freezing columns for horizontal scrolling
- Binding column properties to ViewModel
Covers:
- 15+ built-in column types with usage scenarios
- Manual column definition in XAML and code-behind
- Column properties and configuration options
- Column manipulation methods
- AllowResizing and column width management
- AllowDraggingColumns for reordering
- FrozenColumnsCount for pinned columns
- ViewModel binding for dynamic column configuration
📄 阅读: references/columns.md
阅读时机:
- 手动定义列而非自动生成
- 使用特定列类型(GridTextColumn、GridNumericColumn等)
- 配置列属性(HeaderText、MappingName、Width)
- 管理列操作(添加、删除、重新排序)
- 启用列调整大小和拖放
- 冻结列以支持水平滚动
- 将列属性绑定到ViewModel
涵盖内容:
- 15+种内置列类型及使用场景
- 在XAML和代码后置中手动定义列
- 列属性和配置选项
- 列操作方法
- AllowResizing和列宽管理
- AllowDraggingColumns用于重新排序
- FrozenColumnsCount用于固定列
- 动态列配置的ViewModel绑定
Auto-Sizing Columns
列自动调整大小
📄 Read: references/autosize-columns.md
When to read:
- Implementing automatic column width calculations
- Using ColumnSizer modes (Auto, Star, SizeToCells)
- Filling remaining grid width with specific columns
- Refreshing column sizes at runtime
- Customizing auto-sizing logic
- Implementing star column ratios
- Handling font-based width calculations
Covers:
- ColumnSizer enumeration and modes
- AutoFitColumns() method usage
- ColumnWidthMode for individual columns
- AutoLastColumnFill and AutoWithLastColumnFill
- Refreshing auto-size calculations dynamically
- Custom GridColumnSizer implementation
- Star column sizer ratios and weights
- Font-based width calculation strategies
📄 阅读: references/autosize-columns.md
阅读时机:
- 实现列宽自动计算
- 使用ColumnSizer模式(Auto、Star、SizeToCells)
- 使用特定列填充网格剩余宽度
- 在运行时刷新列大小
- 自定义自动调整逻辑
- 实现星号列比例
- 处理基于字体的宽度计算
涵盖内容:
- ColumnSizer枚举和模式
- AutoFitColumns()方法的使用
- 单个列的ColumnWidthMode
- AutoLastColumnFill和AutoWithLastColumnFill
- 动态刷新自动大小计算
- 自定义GridColumnSizer实现
- 星号列调整器比例和权重
- 基于字体的宽度计算策略
Data Operations
数据操作
Sorting
排序
📄 Read: references/sorting.md
When to read:
- Enabling sorting in the DataGrid
- Implementing single or multi-column sorting
- Adding programmatic sorting
- Creating custom sort logic
- Handling tri-state sorting
- Responding to sorting events
Covers:
- AllowSorting property for enabling sort functionality
- SortColumnDescriptions collection for programmatic sorting
- AllowSorting at column level
- Custom IComparer implementation for sort logic
- SortClickAction (SingleClick, DoubleClick)
- Tri-state sorting configuration
- Sorting events (SortColumnsChanging, SortColumnsChanged)
- Removing sort indicators
📄 阅读: references/sorting.md
阅读时机:
- 在数据网格中启用排序
- 实现单列或多列排序
- 添加程序化排序
- 创建自定义排序逻辑
- 处理三态排序
- 响应排序事件
涵盖内容:
- 用于启用排序功能的AllowSorting属性
- 用于程序化排序的SortColumnDescriptions集合
- 列级别的AllowSorting
- 用于排序逻辑的自定义IComparer实现
- SortClickAction(SingleClick、DoubleClick)
- 三态排序配置
- 排序事件(SortColumnsChanging、SortColumnsChanged)
- 移除排序指示器
Filtering
筛选
📄 Read: references/filtering.md
When to read:
- Implementing data filtering functionality
- Adding programmatic filters with predicates
- Configuring filter row or advanced filter UI
- Creating custom filter logic
- Using Excel-style filtering
- Handling filter events
Covers:
- View filtering with View.Filter predicate
- Column filtering with FilterPredicates
- Filter row implementation (AllowFiltering)
- Advanced filter UI configuration
- Excel-style filter popup
- Custom filter logic and conditions
- FilterChanged and FilterChanging events
- RefreshFilter() method usage
- Filter row customization
📄 阅读: references/filtering.md
阅读时机:
- 实现数据筛选功能
- 使用谓词添加程序化筛选
- 配置筛选行或高级筛选UI
- 创建自定义筛选逻辑
- 使用Excel样式筛选
- 处理筛选事件
涵盖内容:
- 使用View.Filter谓词进行视图筛选
- 使用FilterPredicates进行列筛选
- 筛选行实现(AllowFiltering)
- 高级筛选UI配置
- Excel样式筛选弹出框
- 自定义筛选逻辑和条件
- FilterChanged和FilterChanging事件
- RefreshFilter()方法的使用
- 筛选行自定义
Grouping
分组
📄 Read: references/grouping.md
When to read:
- Enabling data grouping functionality
- Adding programmatic grouping by columns
- Customizing group display and behavior
- Implementing custom grouping logic
- Managing group expand/collapse state
- Adding group summaries
Covers:
- AllowGrouping property configuration
- GroupColumnDescriptions for programmatic grouping
- Drag-drop column headers to group panel
- Custom IGroupComparer implementation
- Group expand/collapse methods
- ShowGroupDropArea property
- Group summaries integration
- Grouping events (GroupExpanding, GroupExpanded, GroupCollapsing, GroupCollapsed)
📄 阅读: references/grouping.md
阅读时机:
- 启用数据分组功能
- 通过列添加程序化分组
- 自定义分组显示和行为
- 实现自定义分组逻辑
- 管理分组展开/折叠状态
- 添加分组汇总
涵盖内容:
- AllowGrouping属性配置
- 用于程序化分组的GroupColumnDescriptions
- 将列标题拖放到分组面板
- 自定义IGroupComparer实现
- 分组展开/折叠方法
- ShowGroupDropArea属性
- 分组汇总集成
- 分组事件(GroupExpanding、GroupExpanded、GroupCollapsing、GroupCollapsed)
Selection
选择
📄 Read: references/selection.md
When to read:
- Configuring selection modes in the grid
- Implementing row or cell selection
- Adding programmatic selection
- Handling selection events
- Using checkbox selection column
Covers:
- SelectionMode (Single, Multiple, Extended, None)
- SelectionUnit (Row, Cell, Any)
- SelectedItem and SelectedItems properties
- SelectedIndex for single selection
- Programmatic selection methods (SelectRow, SelectCell)
- Selection events (SelectionChanging, SelectionChanged)
- CheckBox selection column
- NavigationMode and keyboard selection
📄 阅读: references/selection.md
阅读时机:
- 配置网格中的选择模式
- 实现行或单元格选择
- 添加程序化选择
- 处理选择事件
- 使用复选框选择列
涵盖内容:
- SelectionMode(Single、Multiple、Extended、None)
- SelectionUnit(Row、Cell、Any)
- SelectedItem和SelectedItems属性
- 单选的SelectedIndex
- 程序化选择方法(SelectRow、SelectCell)
- 选择事件(SelectionChanging、SelectionChanged)
- 复选框选择列
- NavigationMode和键盘选择
Editing and Manipulation
编辑与操作
Grid Editing
网格编辑
📄 Read: references/editing.md
When to read:
- Enabling in-line editing in the grid
- Configuring edit modes and triggers
- Implementing column-level editing control
- Adding validation to edited cells
- Creating custom editors for columns
- Managing add/delete row operations
- Handling editing events
Covers:
- AllowEditing property for grid-level control
- AllowEditing at column level
- EditTrigger (OnTap, OnDoubleTap)
- BeginEdit() and EndEdit() methods
- Validation with IDataErrorInfo and INotifyDataErrorInfo
- Custom editor templates
- AddNewRow configuration
- Deleting rows programmatically
- Editing events (CurrentCellBeginEdit, CurrentCellEndEdit, etc.)
📄 阅读: references/editing.md
阅读时机:
- 在网格中启用行内编辑
- 配置编辑模式和触发条件
- 实现列级编辑控制
- 为编辑的单元格添加验证
- 为列创建自定义编辑器
- 管理添加/删除行操作
- 处理编辑事件
涵盖内容:
- 网格级控制的AllowEditing属性
- 列级别的AllowEditing
- EditTrigger(OnTap、OnDoubleTap)
- BeginEdit()和EndEdit()方法
- 使用IDataErrorInfo和INotifyDataErrorInfo进行验证
- 自定义编辑器模板
- AddNewRow配置
- 程序化删除行
- 编辑事件(CurrentCellBeginEdit、CurrentCellEndEdit等)
Data Manipulation
数据操作
📄 Read: references/data-manipulation.md
When to read:
- Adding rows programmatically to the grid
- Deleting rows or clearing data
- Updating cell values in code
- Performing CRUD operations
- Implementing data validation
- Refreshing grid data after changes
Covers:
- View.AddNew() for adding rows
- View.Remove() and View.RemoveAt() for deletion
- Updating data source for cell changes
- CRUD operation patterns
- Data validation strategies
- RefreshView() and Refresh() methods
- CommitEdit() and CancelEdit() operations
- UpdateSourceTrigger configuration
📄 阅读: references/data-manipulation.md
阅读时机:
- 程序化向网格添加行
- 删除行或清除数据
- 在代码中更新单元格值
- 执行CRUD操作
- 实现数据验证
- 数据更改后刷新网格数据
涵盖内容:
- 使用View.AddNew()添加行
- 使用View.Remove()和View.RemoveAt()删除行
- 更新数据源以更改单元格值
- CRUD操作模式
- 数据验证策略
- RefreshView()和Refresh()方法
- CommitEdit()和CancelEdit()操作
- UpdateSourceTrigger配置
Drag and Drop
拖放
📄 Read: references/drag-and-drop.md
When to read:
- Enabling row drag-drop within grid
- Implementing drag-drop between multiple grids
- Configuring column drag-drop
- Customizing drag-drop behavior
- Handling drag-drop events
Covers:
- AllowDraggingRows property
- Row drag-drop within same grid
- Drag-drop between different grids
- AllowDraggingColumns for column reordering
- Drag-drop events (RowDragStarting, RowDragOver, RowDropping, RowDropped)
- Custom drag-drop logic
- Drop position indicators
📄 阅读: references/drag-and-drop.md
阅读时机:
- 启用网格内的行拖放
- 实现多个网格之间的拖放
- 配置列拖放
- 自定义拖放行为
- 处理拖放事件
涵盖内容:
- AllowDraggingRows属性
- 同一网格内的行拖放
- 不同网格之间的拖放
- 用于列重新排序的AllowDraggingColumns
- 拖放事件(RowDragStarting、RowDragOver、RowDropping、RowDropped)
- 自定义拖放逻辑
- 放置位置指示器
Export and Serialization
导出与序列化
Export to Excel and PDF
导出到Excel和PDF
📄 Read: references/export.md
When to read:
- Exporting grid data to Excel format
- Exporting grid to PDF documents
- Customizing export appearance and formatting
- Exporting selected rows only
- Handling export events
- Adding required assemblies for export functionality
Covers:
- ExcelExportingOptions for Excel export
- PdfExportingOptions for PDF export
- ExportToExcel() and ExportToPdf() methods
- Required NuGet packages (Syncfusion.SfGridConverter.WPF)
- Customizing export styles and appearance
- ExportMode (All, SelectedRows)
- Export events (ExcelExportingOptions.CellExporting)
- Excluding columns from export
- Custom cell formatting in exports
📄 阅读: references/export.md
阅读时机:
- 将网格数据导出为Excel格式
- 将网格导出为PDF文档
- 自定义导出外观和格式
- 仅导出选定行
- 处理导出事件
- 添加导出功能所需的程序集
涵盖内容:
- 用于Excel导出的ExcelExportingOptions
- 用于PDF导出的PdfExportingOptions
- ExportToExcel()和ExportToPdf()方法
- 所需NuGet包(Syncfusion.SfGridConverter.WPF)
- 自定义导出样式和外观
- ExportMode(All、SelectedRows)
- 导出事件(ExcelExportingOptions.CellExporting)
- 排除导出列
- 导出中的自定义单元格格式
Advanced Features
高级功能
Summaries
汇总
📄 Read: references/summaries.md
When to read:
- Adding table summaries for entire grid
- Implementing group summaries within groups
- Creating caption summaries in group headers
- Using built-in aggregate functions
- Creating custom summary calculations
- Formatting summary display
Covers:
- GridSummaryRow for table summaries
- TableSummaryRows collection
- GroupSummaryRows for group-level aggregates
- CaptionSummaryRow for group captions
- Built-in aggregates (Count, Sum, Average, Min, Max, etc.)
- Custom aggregate implementation
- Summary display format strings
- SummaryColumns configuration
- ShowSummaryInRow for custom templates
📄 阅读: references/summaries.md
阅读时机:
- 为整个网格添加表格汇总
- 在分组内实现分组汇总
- 在分组标题中创建标题汇总
- 使用内置聚合函数
- 创建自定义汇总计算
- 格式化汇总显示
涵盖内容:
- 用于表格汇总的GridSummaryRow
- TableSummaryRows集合
- 用于分组级聚合的GroupSummaryRows
- 用于分组标题的CaptionSummaryRow
- 内置聚合函数(Count、Sum、Average、Min、Max等)
- 自定义聚合实现
- 汇总显示格式字符串
- SummaryColumns配置
- 用于自定义模板的ShowSummaryInRow
Master-Detail View
主从视图
📄 Read: references/master-detail-view.md
When to read:
- Creating hierarchical grid views
- Implementing master-detail relationships
- Configuring nested grids
- Setting up auto-expanding details
- Supporting multiple detail views
- Customizing detail view templates
Covers:
- DetailsViewDefinition setup
- AutoGenerateRelations property
- Nested SfDataGrid in DetailsViewTemplate
- RelationalColumn for specifying child collection
- ExpandAllDetailsView() method
- Multiple detail view levels
- Custom detail view templates
- Detail view events
📄 阅读: references/master-detail-view.md
阅读时机:
- 创建分层网格视图
- 实现主从关系
- 配置嵌套网格
- 设置自动展开详情
- 支持多个详情视图
- 自定义详情视图模板
涵盖内容:
- DetailsViewDefinition设置
- AutoGenerateRelations属性
- DetailsViewTemplate中的嵌套SfDataGrid
- 用于指定子集合的RelationalColumn
- ExpandAllDetailsView()方法
- 多个详情视图层级
- 自定义详情视图模板
- 详情视图事件
Advanced Configuration
高级配置
📄 Read: references/advanced-features.md
When to read:
- Implementing localization and globalization
- Serializing and deserializing grid state
- Saving and restoring grid configuration
- Supporting multiple languages and cultures
- Persisting user preferences
Covers:
- Localization with ResourceManager and Resx files
- Setting CurrentUICulture for language support
- Creating culture-specific resource files
- Serialization options (SerializationOptions)
- Serialize() and Deserialize() methods
- Saving grid state to XML file or stream
- Restoring grid configuration from file
- Custom column serialization with SerializationController
- Performance tips (UI virtualization, NotifyListChangedAction)
- AllowFrozenGroupHeaders option
📄 阅读: references/advanced-features.md
阅读时机:
- 实现本地化和全球化
- 序列化和反序列化网格状态
- 保存和恢复网格配置
- 支持多种语言和文化
- 持久化用户偏好
涵盖内容:
- 使用ResourceManager和Resx文件进行本地化
- 设置CurrentUICulture以支持多语言
- 创建特定文化的资源文件
- 序列化选项(SerializationOptions)
- Serialize()和Deserialize()方法
- 将网格状态保存到XML文件或流
- 从文件恢复网格配置
- 使用SerializationController进行自定义列序列化
- 性能提示(UI虚拟化、NotifyListChangedAction)
- AllowFrozenGroupHeaders选项
Styling and Customization
样式与自定义
📄 Read: references/styling.md
When to read:
- Applying cell styling and conditional formatting
- Customizing row appearance
- Implementing alternate row styles
- Creating conditional styling based on data
- Styling headers, summaries, and group rows
- Applying themes with SfSkinManager
Covers:
- CellStyle for uniform cell styling
- CellStyleSelector for conditional cell formatting
- RowStyle and RowStyleSelector for row appearance
- AlternatingRowStyle for zebra striping
- HeaderStyle for column headers
- GroupCaptionStyle for group rows
- SummaryCellStyle for summary rows
- SfSkinManager for theme application
- Style triggers and data binding in styles
- Visual states (Normal, Selected, Current)
📄 阅读: references/styling.md
阅读时机:
- 应用单元格样式和条件格式
- 自定义行外观
- 实现交替行样式
- 根据数据创建条件样式
- 样式化表头、汇总和分组行
- 使用SfSkinManager应用主题
涵盖内容:
- 用于统一单元格样式的CellStyle
- 用于条件单元格格式的CellStyleSelector
- 用于行外观的RowStyle和RowStyleSelector
- 用于斑马纹的AlternatingRowStyle
- 用于列头的HeaderStyle
- 用于分组行的GroupCaptionStyle
- 用于汇总行的SummaryCellStyle
- 用于主题应用的SfSkinManager
- 样式触发器和样式中的数据绑定
- 视觉状态(Normal、Selected、Current)
Quick Start Example
快速入门示例
Here's a minimal example to get started with SfDataGrid in WPF:
以下是在WPF中使用SfDataGrid的最简示例:
XAML
XAML
xml
<Window x:Class="DataGridDemo.MainWindow"
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">
<Grid>
<syncfusion:SfDataGrid x:Name="dataGrid"
AutoGenerateColumns="True"
AllowSorting="True"
AllowFiltering="True"
AllowGrouping="True"
AllowEditing="True"
ItemsSource="{Binding Orders}">
</syncfusion:SfDataGrid>
</Grid>
</Window>xml
<Window x:Class="DataGridDemo.MainWindow"
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">
<Grid>
<syncfusion:SfDataGrid x:Name="dataGrid"
AutoGenerateColumns="True"
AllowSorting="True"
AllowFiltering="True"
AllowGrouping="True"
AllowEditing="True"
ItemsSource="{Binding Orders}">
</syncfusion:SfDataGrid>
</Grid>
</Window>Code-Behind with ViewModel
带ViewModel的代码后置
csharp
using System.Collections.ObjectModel;
using System.ComponentModel;
using Syncfusion.UI.Xaml.Grid;
public class OrderInfo : INotifyPropertyChanged
{
private string orderId;
private string customerName;
private string country;
private decimal orderTotal;
public string OrderID
{
get => orderId;
set { orderId = value; OnPropertyChanged(nameof(OrderID)); }
}
public string CustomerName
{
get => customerName;
set { customerName = value; OnPropertyChanged(nameof(CustomerName)); }
}
public string Country
{
get => country;
set { country = value; OnPropertyChanged(nameof(Country)); }
}
public decimal OrderTotal
{
get => orderTotal;
set { orderTotal = value; OnPropertyChanged(nameof(OrderTotal)); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ViewModel
{
public ObservableCollection<OrderInfo> Orders { get; set; }
public ViewModel()
{
Orders = new ObservableCollection<OrderInfo>
{
new OrderInfo { OrderID = "1001", CustomerName = "John Doe", Country = "USA", OrderTotal = 1500.50m },
new OrderInfo { OrderID = "1002", CustomerName = "Jane Smith", Country = "UK", OrderTotal = 2300.75m },
new OrderInfo { OrderID = "1003", CustomerName = "Bob Johnson", Country = "Canada", OrderTotal = 890.25m }
};
}
}csharp
using System.Collections.ObjectModel;
using System.ComponentModel;
using Syncfusion.UI.Xaml.Grid;
public class OrderInfo : INotifyPropertyChanged
{
private string orderId;
private string customerName;
private string country;
private decimal orderTotal;
public string OrderID
{
get => orderId;
set { orderId = value; OnPropertyChanged(nameof(OrderID)); }
}
public string CustomerName
{
get => customerName;
set { customerName = value; OnPropertyChanged(nameof(CustomerName)); }
}
public string Country
{
get => country;
set { country = value; OnPropertyChanged(nameof(Country)); }
}
public decimal OrderTotal
{
get => orderTotal;
set { orderTotal = value; OnPropertyChanged(nameof(OrderTotal)); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ViewModel
{
public ObservableCollection<OrderInfo> Orders { get; set; }
public ViewModel()
{
Orders = new ObservableCollection<OrderInfo>
{
new OrderInfo { OrderID = "1001", CustomerName = "John Doe", Country = "USA", OrderTotal = 1500.50m },
new OrderInfo { OrderID = "1002", CustomerName = "Jane Smith", Country = "UK", OrderTotal = 2300.75m },
new OrderInfo { OrderID = "1003", CustomerName = "Bob Johnson", Country = "Canada", OrderTotal = 890.25m }
};
}
}Common Patterns
常见模式
MVVM Data Binding Pattern
MVVM数据绑定模式
csharp
// ViewModel property
public ObservableCollection<Employee> Employees { get; set; }
// XAML binding
<syncfusion:SfDataGrid ItemsSource="{Binding Employees}" />csharp
// ViewModel属性
public ObservableCollection<Employee> Employees { get; set; }
// XAML绑定
<syncfusion:SfDataGrid ItemsSource="{Binding Employees}" />Manual Column Definition
手动列定义
xml
<syncfusion:SfDataGrid AutoGenerateColumns="False" ItemsSource="{Binding Orders}">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="OrderID" HeaderText="Order ID" Width="120"/>
<syncfusion:GridTextColumn MappingName="CustomerName" HeaderText="Customer" Width="150"/>
<syncfusion:GridNumericColumn MappingName="OrderTotal" HeaderText="Total"
NumberDecimalDigits="2" Width="120"/>
<syncfusion:GridDateTimeColumn MappingName="OrderDate" HeaderText="Date"
Pattern="ShortDate" Width="120"/>
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>xml
<syncfusion:SfDataGrid AutoGenerateColumns="False" ItemsSource="{Binding Orders}">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="OrderID" HeaderText="Order ID" Width="120"/>
<syncfusion:GridTextColumn MappingName="CustomerName" HeaderText="Customer" Width="150"/>
<syncfusion:GridNumericColumn MappingName="OrderTotal" HeaderText="Total"
NumberDecimalDigits="2" Width="120"/>
<syncfusion:GridDateTimeColumn MappingName="OrderDate" HeaderText="Date"
Pattern="ShortDate" Width="120"/>
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>Programmatic Sorting
程序化排序
csharp
// Add sort description
dataGrid.SortColumnDescriptions.Add(new SortColumnDescription
{
ColumnName = "OrderTotal",
SortDirection = ListSortDirection.Descending
});csharp
// 添加排序描述
dataGrid.SortColumnDescriptions.Add(new SortColumnDescription
{
ColumnName = "OrderTotal",
SortDirection = ListSortDirection.Descending
});Programmatic Filtering
程序化筛选
csharp
// Set filter predicate
dataGrid.View.Filter = (obj) =>
{
var order = obj as OrderInfo;
return order != null && order.OrderTotal > 1000;
};
dataGrid.View.RefreshFilter();csharp
// 设置筛选谓词
dataGrid.View.Filter = (obj) =>
{
var order = obj as OrderInfo;
return order != null && order.OrderTotal > 1000;
};
dataGrid.View.RefreshFilter();Selection Handling
选择处理
csharp
// Handle selection changed
dataGrid.SelectionChanged += (sender, e) =>
{
var selectedItem = dataGrid.SelectedItem as OrderInfo;
if (selectedItem != null)
{
MessageBox.Show($"Selected Order: {selectedItem.OrderID}");
}
};csharp
// 处理选择更改
dataGrid.SelectionChanged += (sender, e) =>
{
var selectedItem = dataGrid.SelectedItem as OrderInfo;
if (selectedItem != null)
{
MessageBox.Show($"Selected Order: {selectedItem.OrderID}");
}
};Export to Excel
导出到Excel
csharp
using Syncfusion.UI.Xaml.Grid.Converter;
var options = new ExcelExportingOptions
{
ExcelVersion = ExcelVersion.Excel2013
};
dataGrid.ExportToExcel(dataGrid.View, options);csharp
using Syncfusion.UI.Xaml.Grid.Converter;
var options = new ExcelExportingOptions
{
ExcelVersion = ExcelVersion.Excel2013
};
dataGrid.ExportToExcel(dataGrid.View, options);Key Properties
关键属性
Core Properties
核心属性
- ItemsSource: Data source for the grid (IEnumerable)
- AutoGenerateColumns: Automatically create columns from data source (bool)
- Columns: Collection of manually defined columns
- ItemsSource:网格的数据源(IEnumerable)
- AutoGenerateColumns:自动从数据源创建列(bool)
- Columns:手动定义的列集合
Data Operation Properties
数据操作属性
- AllowSorting: Enable column sorting (bool)
- AllowFiltering: Enable filtering functionality (bool)
- AllowGrouping: Enable grouping by columns (bool)
- AllowEditing: Enable in-line editing (bool)
- AllowSorting:启用列排序(bool)
- AllowFiltering:启用筛选功能(bool)
- AllowGrouping:启用按列分组(bool)
- AllowEditing:启用行内编辑(bool)
Column Configuration
列配置属性
- ColumnSizer: Auto-sizing strategy for columns
- FrozenColumnsCount: Number of columns frozen from left (int)
- AllowResizingColumns: Enable column resizing (bool)
- AllowDraggingColumns: Enable column reordering (bool)
- ColumnSizer:列的自动调整策略
- FrozenColumnsCount:左侧固定的列数(int)
- AllowResizingColumns:启用列调整大小(bool)
- AllowDraggingColumns:启用列重新排序(bool)
Selection Properties
选择属性
- SelectionMode: Selection behavior (Single, Multiple, Extended, None)
- SelectionUnit: Unit of selection (Row, Cell, Any)
- SelectedItem: Currently selected item (object)
- SelectedItems: Collection of selected items
- SelectionMode:选择行为(Single、Multiple、Extended、None)
- SelectionUnit:选择单位(Row、Cell、Any)
- SelectedItem:当前选中的项(object)
- SelectedItems:选中项的集合
Visual Properties
视觉属性
- HeaderRowHeight: Height of column header row (double)
- RowHeight: Default height for data rows (double)
- GridLinesVisibility: Visibility of grid lines (Both, Horizontal, Vertical, None)
- HeaderRowHeight:列头行的高度(double)
- RowHeight:数据行的默认高度(double)
- GridLinesVisibility:网格线的可见性(Both、Horizontal、Vertical、None)
Common Use Cases
常见用例
Business Applications
业务应用
Create data entry forms with editable grids, validation, and CRUD operations for managing business records like orders, customers, or inventory.
创建带可编辑网格、验证和CRUD操作的数据输入表单,用于管理订单、客户或库存等业务记录。
Data Analysis and Reporting
数据分析与报告
Display large datasets with sorting, filtering, grouping, and summaries for analyzing sales data, financial reports, or statistical information.
显示大型数据集,支持排序、筛选、分组和汇总,用于分析销售数据、财务报告或统计信息。
Master-Detail Views
主从视图
Show hierarchical data relationships with expandable detail views for order-line items, customer-orders, or category-products structures.
显示分层数据关系,带可展开的详情视图,用于订单行项目、客户-订单或类别-产品结构。
Data Export and Printing
数据导出与打印
Export filtered and grouped data to Excel or PDF for sharing reports, creating backups, or printing formatted documents.
将筛选和分组的数据导出为Excel或PDF,用于共享报告、创建备份或打印格式化文档。
Dashboard and Monitoring
仪表板与监控
Build real-time data monitoring grids with auto-refresh, conditional styling for alerts, and summary rows for KPIs.
Next Steps: Navigate to the specific reference documentation above based on your implementation needs. Start with getting-started.md for initial setup, then explore feature-specific guides as required.
构建带自动刷新、警报条件样式和KPI汇总行的实时数据监控网格。
下一步: 根据你的实现需求,导航到上述特定参考文档。从getting-started.md开始进行初始设置,然后根据需要探索特定功能的指南。