syncfusion-wpf-treegrid

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing WPF TreeGrid (SfTreeGrid)

实现WPF TreeGrid(SfTreeGrid)

Comprehensive guide for implementing the Syncfusion® WPF TreeGrid control - a data-oriented control that displays self-relational and hierarchical data in a tree structure with columns. This skill provides complete guidance for setup, data binding, column configuration, interactive features, data operations, styling, and advanced capabilities.
本文是实现Syncfusion® WPF TreeGrid控件的综合指南——这是一款面向数据的控件,可在带列的树形结构中显示自关联和层级数据。本指南提供了关于设置、数据绑定、列配置、交互功能、数据操作、样式设置及高级功能的完整指导。

When to Use This Skill

何时使用本技能

Use this skill when you need to:
  • Display hierarchical data in a grid with expandable/collapsible tree structure
  • Bind self-relational data (parent-child relationships within single collection)
  • Bind nested collections with parent-child object hierarchies
  • Implement load-on-demand for large hierarchical datasets
  • Configure columns with various types (text, numeric, datetime, checkbox, combo box)
  • Enable editing in tree grid with validation
  • Implement sorting and filtering on hierarchical data
  • Customize selection behavior (single, multiple, row, cell)
  • Apply conditional styling based on data or node level
  • Merge cells across columns in tree grid rows
  • Export tree grids to Excel or PDF formats
  • Implement MVVM patterns with TreeGrid controls
  • Customize appearance with themes, styles, and templates
This skill is essential for any WPF application that needs to present hierarchical or parent-child data in an interactive, feature-rich grid interface.
当你需要以下功能时,可使用本技能:
  • 显示层级数据:在带可展开/折叠树形结构的网格中展示数据
  • 绑定自关联数据:(单个集合内的父子关系)
  • 绑定嵌套集合:带父子对象层级的嵌套集合
  • 实现按需加载:针对大型层级数据集
  • 配置列:支持多种类型(文本、数值、日期时间、复选框、下拉框)
  • 启用编辑:树形网格中的编辑功能及验证
  • 实现排序与筛选:针对层级数据
  • 自定义选择行为:(单选、多选、行选择、单元格选择)
  • 应用条件样式:基于数据或节点层级
  • 合并单元格:树形网格行中跨列合并单元格
  • 导出树形网格:导出为Excel或PDF格式
  • 实现MVVM模式:结合TreeGrid控件使用
  • 自定义外观:通过主题、样式和模板
对于需要以交互式、功能丰富的网格界面展示层级或父子数据的WPF应用而言,本技能至关重要。

Component Overview

组件概述

The SfTreeGrid control provides:
  • Hierarchical Data Display: Self-relational and nested collection binding
  • Multiple Column Types: Text, Numeric, DateTime, CheckBox, ComboBox, Hyperlink, and Template columns
  • Interactive Features: Editing, selection, sorting, filtering, drag-drop
  • Data Operations: Sorting, filtering with multiple filter levels (Root, All, Extended)
  • Load-On-Demand: Efficient loading of child nodes on expansion
  • Cell Merging: Merge adjacent cells across columns
  • Export Capabilities: Export to Excel and PDF with customization
  • Styling: Conditional styling, themes, templates, and visual customization
  • MVVM Support: Complete MVVM pattern compatibility with command binding
  • Performance: Virtualization and optimized rendering for large datasets
SfTreeGrid控件提供以下功能:
  • 层级数据展示:支持自关联和嵌套集合绑定
  • 多种列类型:文本、数值、日期时间、复选框、下拉框、超链接及模板列
  • 交互功能:编辑、选择、排序、筛选、拖放
  • 数据操作:排序、多级别筛选(根节点、全部、扩展)
  • 按需加载:展开节点时高效加载子节点
  • 单元格合并:跨列合并相邻单元格
  • 导出功能:可自定义的Excel和PDF导出
  • 样式设置:条件样式、主题、模板及视觉自定义
  • MVVM支持:完全兼容MVVM模式及命令绑定
  • 性能优化:虚拟化及针对大型数据集的优化渲染

Documentation and Navigation Guide

文档与导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
Start here for initial setup and basic implementation:
  • Assembly deployment (Syncfusion.SfGrid.WPF, Syncfusion.Data.WPF, Syncfusion.Shared.WPF)
  • Creating WPF project with TreeGrid
  • Adding control via Designer, XAML, or code-behind
  • Basic TreeGrid setup examples
  • Simple self-relational and nested collection binding
📄 阅读references/getting-started.md
从这里开始进行初始设置和基础实现:
  • 程序集部署(Syncfusion.SfGrid.WPF、Syncfusion.Data.WPF、Syncfusion.Shared.WPF)
  • 创建带TreeGrid的WPF项目
  • 通过设计器、XAML或代码后置添加控件
  • 基础TreeGrid设置示例
  • 简单的自关联和嵌套集合绑定

Data Binding & Operations

数据绑定与操作

Data Binding Approaches
📄 Read: references/data-binding.md
  • Self-relational data binding (ParentPropertyName, ChildPropertyName)
  • Nested collection binding (ChildPropertyName)
  • IEnumerable collection support
  • Dynamic data object binding
  • INotifyCollectionChanged and ObservableCollection
  • Data refresh and updates
Load-On-Demand
📄 Read: references/load-on-demand.md
  • RequestTreeItems event for on-demand loading
  • LoadOnDemandCommand for MVVM scenarios
  • Lazy loading child nodes on expansion
  • Performance optimization for large datasets
  • Populating nodes indicator display
数据绑定方式
📄 阅读references/data-binding.md
  • 自关联数据绑定(ParentPropertyName、ChildPropertyName)
  • 嵌套集合绑定(ChildPropertyName)
  • 支持IEnumerable集合
  • 动态数据对象绑定
  • INotifyCollectionChanged和ObservableCollection
  • 数据刷新与更新
按需加载
📄 阅读references/load-on-demand.md
  • 用于按需加载的RequestTreeItems事件
  • 适用于MVVM场景的LoadOnDemandCommand
  • 展开节点时延迟加载子节点
  • 针对大型数据集的性能优化
  • 节点填充指示器显示

Column Configuration

列配置

Column Basics
📄 Read: references/columns.md
  • Adding and removing columns
  • AutoGenerateColumns vs manual configuration
  • Column properties (HeaderText, MappingName, Width, Alignment)
  • Column visibility and frozen columns
  • Column reordering and resizing
  • Text wrapping and trimming
Column Types
📄 Read: references/column-types.md
  • TreeGridTextColumn for string data
  • TreeGridNumericColumn with number formatting
  • TreeGridDateTimeColumn with date patterns
  • TreeGridCheckBoxColumn for boolean values
  • TreeGridComboBoxColumn for dropdown selection
  • TreeGridHyperlinkColumn for clickable links
  • TreeGridTemplateColumn for custom content
  • Creating custom column types
Column Sizing
📄 Read: references/column-sizing.md
  • ColumnSizer property (Auto, Star, SizeToCells, SizeToHeader)
  • Auto-fitting columns to content
  • Manual width specification
  • User resizing behavior
  • Min and Max width constraints
  • Fill remaining space strategies
列基础
📄 阅读references/columns.md
  • 添加和移除列
  • 自动生成列 vs 手动配置
  • 列属性(HeaderText、MappingName、Width、Alignment)
  • 列可见性与冻结列
  • 列重排序与调整大小
  • 文本换行与截断
列类型
📄 阅读references/column-types.md
  • TreeGridTextColumn:用于字符串数据
  • TreeGridNumericColumn:带数字格式化
  • TreeGridDateTimeColumn:带日期格式
  • TreeGridCheckBoxColumn:用于布尔值
  • TreeGridComboBoxColumn:用于下拉选择
  • TreeGridHyperlinkColumn:用于可点击链接
  • TreeGridTemplateColumn:用于自定义内容
  • 创建自定义列类型
列尺寸调整
📄 阅读references/column-sizing.md
  • ColumnSizer属性(Auto、Star、SizeToCells、SizeToHeader)
  • 根据内容自动适配列宽
  • 手动指定宽度
  • 用户调整大小的行为
  • 最小和最大宽度限制
  • 剩余空间填充策略

Interactive Features

交互功能

Editing
📄 Read: references/editing.md
  • AllowEditing property for grid and column level
  • Edit modes (OnTap, OnDoubleTap)
  • Edit triggers and edit template customization
  • BeginEdit and EndEdit events
  • Programmatic editing (BeginEdit, EndEdit, CurrentCell)
  • Validation during editing
Data Validation
📄 Read: references/data-validation.md
  • IDataErrorInfo validation interface
  • INotifyDataErrorInfo support
  • Cell-level and row-level validation
  • Custom validation rules
  • Validation error display customization
  • Handling validation errors
Selection
📄 Read: references/selection.md
  • SelectionMode (Single, Multiple, Extended, None)
  • SelectionUnit (Row, Cell, Any)
  • SelectedItem and SelectedItems binding
  • CurrentCell and CurrentItem properties
  • Programmatic selection
  • SelectionChanged and CurrentCellActivated events
Cell Merging
📄 Read: references/merge-cells.md
  • QueryCoveredRange event for merging cells
  • Column-wise merging by fixed range
  • Merging based on cell content
  • Navigation and selection in merged cells
  • Performance considerations for cell merging
编辑
📄 阅读references/editing.md
  • 网格和列级别的AllowEditing属性
  • 编辑模式(OnTap、OnDoubleTap)
  • 编辑触发条件与编辑模板自定义
  • BeginEdit和EndEdit事件
  • 程序化编辑(BeginEdit、EndEdit、CurrentCell)
  • 编辑时的验证
数据验证
📄 阅读references/data-validation.md
  • IDataErrorInfo验证接口
  • INotifyDataErrorInfo支持
  • 单元格级和行级验证
  • 自定义验证规则
  • 验证错误显示自定义
  • 处理验证错误
选择
📄 阅读references/selection.md
  • SelectionMode(Single、Multiple、Extended、None)
  • SelectionUnit(Row、Cell、Any)
  • SelectedItem和SelectedItems绑定
  • CurrentCell和CurrentItem属性
  • 程序化选择
  • SelectionChanged和CurrentCellActivated事件
单元格合并
📄 阅读references/merge-cells.md
  • 用于合并单元格的QueryCoveredRange事件
  • 按固定范围进行列级合并
  • 基于单元格内容的合并
  • 合并单元格中的导航与选择
  • 单元格合并的性能考量

Data Operations

数据操作

Sorting
📄 Read: references/sorting.md
  • AllowSorting property (grid and column level)
  • Single and multi-column sorting
  • Tri-state sorting (ascending, descending, unsorted)
  • Programmatic sorting with SortColumnDescriptions
  • Custom sorting logic with IComparer
  • SortColumnsChanging and SortColumnsChanged events
Filtering
📄 Read: references/filtering.md
  • FilterLevel (Root, All, Extended) for hierarchical filtering
  • Advanced filter UI with filter row
  • Programmatic filtering with FilterPredicates
  • Custom filter logic
  • FilterChanging and FilterChanged events
  • Clearing and persisting filters
排序
📄 阅读references/sorting.md
  • 网格和列级别的AllowSorting属性
  • 单列和多列排序
  • 三态排序(升序、降序、未排序)
  • 使用SortColumnDescriptions进行程序化排序
  • 结合IComparer的自定义排序逻辑
  • SortColumnsChanging和SortColumnsChanged事件
筛选
📄 阅读references/filtering.md
  • FilterLevel(Root、All、Extended):用于层级筛选
  • 带筛选行的高级筛选UI
  • 使用FilterPredicates进行程序化筛选
  • 自定义筛选逻辑
  • FilterChanging和FilterChanged事件
  • 清除和保留筛选条件

Styling & Customization

样式与自定义

Conditional Styling
📄 Read: references/conditional-styling.md
  • StyleSelector for row and cell styling
  • RowStyleSelector for row-based formatting
  • CellStyleSelector for cell-based formatting
  • Conditional formatting based on data values
  • Node level-based styling (parent vs child)
  • Alternating row styles
Styles and Templates
📄 Read: references/styles-and-templates.md
  • CellTemplate and EditTemplate customization
  • HeaderTemplate for column headers
  • ExpanderTemplate for expand/collapse buttons
  • RowHeaderTemplate customization
  • Cell and row styling
  • Visual states and triggers
  • Theme integration
条件样式
📄 阅读references/conditional-styling.md
  • 用于行和单元格样式的StyleSelector
  • 基于行的格式化:RowStyleSelector
  • 基于单元格的格式化:CellStyleSelector
  • 基于数据值的条件格式化
  • 基于节点层级的样式(父节点 vs 子节点)
  • 交替行样式
样式与模板
📄 阅读references/styles-and-templates.md
  • CellTemplate和EditTemplate自定义
  • 列头的HeaderTemplate
  • 展开/折叠按钮的ExpanderTemplate
  • RowHeaderTemplate自定义
  • 单元格和行样式
  • 视觉状态与触发器
  • 主题集成

Advanced Features

高级功能

Export and Printing
📄 Read: references/export-and-printing.md
  • Export to Excel (ExportToExcel method)
  • Export to PDF (ExportToPdf method)
  • TreeGridExcelExportingOptions customization
  • TreeGridPdfExportingOptions customization
  • Print functionality (PrintSettings)
  • Exporting specific nodes and columns
Advanced Configuration
📄 Read: references/advanced-features.md
  • MVVM pattern implementation with ICommand
  • GridLinesVisibility customization (Both, Horizontal, Vertical, None)
  • Serialization and Deserialization (Save/LoadSettings)
  • Localization (ResourceManager)
  • UI Automation support for accessibility
  • Theming (MaterialLight, MaterialDark, Office2019, etc.)
  • Helper methods and utilities
  • NodeCheckBox for node selection
  • ToolTip customization
导出与打印
📄 阅读references/export-and-printing.md
  • 导出到Excel(ExportToExcel方法)
  • 导出到PDF(ExportToPdf方法)
  • TreeGridExcelExportingOptions自定义
  • TreeGridPdfExportingOptions自定义
  • 打印功能(PrintSettings)
  • 导出特定节点和列
高级配置
📄 阅读references/advanced-features.md
  • 结合ICommand实现MVVM模式
  • GridLinesVisibility自定义(Both、Horizontal、Vertical、None)
  • 序列化与反序列化(Save/LoadSettings)
  • 本地化(ResourceManager)
  • 辅助功能的UI自动化支持
  • 主题(MaterialLight、MaterialDark、Office2019等)
  • 辅助方法与工具
  • 用于节点选择的NodeCheckBox
  • ToolTip自定义

Quick Start Example

快速入门示例

Basic Self-Relational TreeGrid

基础自关联TreeGrid

xml
<Window x:Class="TreeGridSample.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">
    
    <syncfusion:SfTreeGrid Name="treeGrid"
                           AutoGenerateColumns="True"
                           ChildPropertyName="Children"
                           ItemsSource="{Binding Employees}"
                           AllowSorting="True"
                           AllowFiltering="True"
                           AllowEditing="True">
    </syncfusion:SfTreeGrid>
</Window>
csharp
using Syncfusion.UI.Xaml.TreeGrid;
using System.Collections.ObjectModel;

namespace TreeGridSample
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public int ReportsTo { get; set; }
        public ObservableCollection<Employee> Children { get; set; }
        
        public Employee()
        {
            Children = new ObservableCollection<Employee>();
        }
    }

    public class EmployeeViewModel
    {
        public ObservableCollection<Employee> Employees { get; set; }
        
        public EmployeeViewModel()
        {
            Employees = new ObservableCollection<Employee>();
            PopulateData();
        }
        
        private void PopulateData()
        {
            var ceo = new Employee
            {
                EmployeeID = 1,
                FirstName = "Robert",
                LastName = "King",
                Title = "CEO"
            };
            
            ceo.Children.Add(new Employee
            {
                EmployeeID = 2,
                FirstName = "David",
                LastName = "Smith",
                Title = "VP of Sales",
                ReportsTo = 1
            });
            
            ceo.Children.Add(new Employee
            {
                EmployeeID = 3,
                FirstName = "Nancy",
                LastName = "Davolio",
                Title = "VP of Marketing",
                ReportsTo = 1
            });
            
            Employees.Add(ceo);
        }
    }
}
xml
<Window x:Class="TreeGridSample.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">
    
    <syncfusion:SfTreeGrid Name="treeGrid"
                           AutoGenerateColumns="True"
                           ChildPropertyName="Children"
                           ItemsSource="{Binding Employees}"
                           AllowSorting="True"
                           AllowFiltering="True"
                           AllowEditing="True">
    </syncfusion:SfTreeGrid>
</Window>
csharp
using Syncfusion.UI.Xaml.TreeGrid;
using System.Collections.ObjectModel;

namespace TreeGridSample
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public int ReportsTo { get; set; }
        public ObservableCollection<Employee> Children { get; set; }
        
        public Employee()
        {
            Children = new ObservableCollection<Employee>();
        }
    }

    public class EmployeeViewModel
    {
        public ObservableCollection<Employee> Employees { get; set; }
        
        public EmployeeViewModel()
        {
            Employees = new ObservableCollection<Employee>();
            PopulateData();
        }
        
        private void PopulateData()
        {
            var ceo = new Employee
            {
                EmployeeID = 1,
                FirstName = "Robert",
                LastName = "King",
                Title = "CEO"
            };
            
            ceo.Children.Add(new Employee
            {
                EmployeeID = 2,
                FirstName = "David",
                LastName = "Smith",
                Title = "VP of Sales",
                ReportsTo = 1
            });
            
            ceo.Children.Add(new Employee
            {
                EmployeeID = 3,
                FirstName = "Nancy",
                LastName = "Davolio",
                Title = "VP of Marketing",
                ReportsTo = 1
            });
            
            Employees.Add(ceo);
        }
    }
}

Common Patterns

常见模式

Pattern 1: Self-Relational Data Binding

模式1:自关联数据绑定

For data where parent-child relationship exists within the same collection:
csharp
public class Task
{
    public int TaskID { get; set; }
    public string TaskName { get; set; }
    public int? ParentID { get; set; }  // Nullable for root items
}

// ViewModel
public ObservableCollection<Task> Tasks { get; set; }
xml
<syncfusion:SfTreeGrid Name="treeGrid"
                       ItemsSource="{Binding Tasks}"
                       ParentPropertyName="ParentID"
                       SelfRelationRootValue="-1"
                       ChildPropertyName="TaskID">
</syncfusion:SfTreeGrid>
适用于父子关系存在于同一集合中的数据:
csharp
public class Task
{
    public int TaskID { get; set; }
    public string TaskName { get; set; }
    public int? ParentID { get; set; }  // 根项可为空
}

// 视图模型
public ObservableCollection<Task> Tasks { get; set; }
xml
<syncfusion:SfTreeGrid Name="treeGrid"
                       ItemsSource="{Binding Tasks}"
                       ParentPropertyName="ParentID"
                       SelfRelationRootValue="-1"
                       ChildPropertyName="TaskID">
</syncfusion:SfTreeGrid>

Pattern 2: Nested Collection Binding

模式2:嵌套集合绑定

For data with explicit child collections:
csharp
public class Folder
{
    public string FolderName { get; set; }
    public ObservableCollection<Folder> SubFolders { get; set; }
}
xml
<syncfusion:SfTreeGrid Name="treeGrid"
                       ItemsSource="{Binding Folders}"
                       ChildPropertyName="SubFolders">
</syncfusion:SfTreeGrid>
适用于带显式子集合的数据:
csharp
public class Folder
{
    public string FolderName { get; set; }
    public ObservableCollection<Folder> SubFolders { get; set; }
}
xml
<syncfusion:SfTreeGrid Name="treeGrid"
                       ItemsSource="{Binding Folders}"
                       ChildPropertyName="SubFolders">
</syncfusion:SfTreeGrid>

Pattern 3: Load-On-Demand with RequestTreeItems

模式3:结合RequestTreeItems的按需加载

For large datasets where child nodes load when parent expands:
csharp
treeGrid.RequestTreeItems += TreeGrid_RequestTreeItems;

private void TreeGrid_RequestTreeItems(object sender, TreeGridRequestTreeItemsEventArgs e)
{
    if (e.ParentItem == null)
    {
        // Load root nodes
        e.ChildItems = GetRootNodes();
    }
    else
    {
        // Load child nodes for expanded parent
        var parent = e.ParentItem as BusinessObject;
        e.ChildItems = GetChildNodes(parent.ID);
    }
}
适用于大型数据集,展开父节点时加载子节点:
csharp
treeGrid.RequestTreeItems += TreeGrid_RequestTreeItems;

private void TreeGrid_RequestTreeItems(object sender, TreeGridRequestTreeItemsEventArgs e)
{
    if (e.ParentItem == null)
    {
        // 加载根节点
        e.ChildItems = GetRootNodes();
    }
    else
    {
        // 加载展开父节点的子节点
        var parent = e.ParentItem as BusinessObject;
        e.ChildItems = GetChildNodes(parent.ID);
    }
}

Pattern 4: Custom Column Definition

模式4:自定义列定义

xml
<syncfusion:SfTreeGrid ItemsSource="{Binding Employees}"
                       AutoGenerateColumns="False">
    <syncfusion:SfTreeGrid.Columns>
        <syncfusion:TreeGridTextColumn HeaderText="Name" 
                                       MappingName="FirstName"
                                       Width="150"/>
        <syncfusion:TreeGridNumericColumn HeaderText="Age" 
                                          MappingName="Age"
                                          NumberDecimalDigits="0"/>
        <syncfusion:TreeGridDateTimeColumn HeaderText="DOB" 
                                           MappingName="DateOfBirth"
                                           FormatString="MM/dd/yyyy"/>
        <syncfusion:TreeGridCheckBoxColumn HeaderText="Active" 
                                           MappingName="IsActive"/>
    </syncfusion:SfTreeGrid.Columns>
</syncfusion:SfTreeGrid>
xml
<syncfusion:SfTreeGrid ItemsSource="{Binding Employees}"
                       AutoGenerateColumns="False">
    <syncfusion:SfTreeGrid.Columns>
        <syncfusion:TreeGridTextColumn HeaderText="姓名" 
                                       MappingName="FirstName"
                                       Width="150"/>
        <syncfusion:TreeGridNumericColumn HeaderText="年龄" 
                                          MappingName="Age"
                                          NumberDecimalDigits="0"/>
        <syncfusion:TreeGridDateTimeColumn HeaderText="出生日期" 
                                           MappingName="DateOfBirth"
                                           FormatString="MM/dd/yyyy"/>
        <syncfusion:TreeGridCheckBoxColumn HeaderText="在职" 
                                           MappingName="IsActive"/>
    </syncfusion:SfTreeGrid.Columns>
</syncfusion:SfTreeGrid>

Pattern 5: MVVM Command Binding

模式5:MVVM命令绑定

xml
<syncfusion:SfTreeGrid ItemsSource="{Binding Employees}"
                       ChildPropertyName="Children">
    <syncfusion:SfTreeGrid.RecordContextMenu>
        <ContextMenu>
            <MenuItem Header="Add Child" 
                      Command="{Binding AddChildCommand}"
                      CommandParameter="{Binding}"/>
            <MenuItem Header="Delete" 
                      Command="{Binding DeleteCommand}"
                      CommandParameter="{Binding}"/>
        </ContextMenu>
    </syncfusion:SfTreeGrid.RecordContextMenu>
</syncfusion:SfTreeGrid>
csharp
public class EmployeeViewModel : INotifyPropertyChanged
{
    public ICommand AddChildCommand { get; set; }
    public ICommand DeleteCommand { get; set; }
    
    public EmployeeViewModel()
    {
        AddChildCommand = new RelayCommand(AddChild);
        DeleteCommand = new RelayCommand(Delete);
    }
    
    private void AddChild(object parameter)
    {
        var parent = parameter as Employee;
        if (parent != null)
        {
            parent.Children.Add(new Employee { /* ... */ });
        }
    }
}
xml
<syncfusion:SfTreeGrid ItemsSource="{Binding Employees}"
                       ChildPropertyName="Children">
    <syncfusion:SfTreeGrid.RecordContextMenu>
        <ContextMenu>
            <MenuItem Header="添加子项" 
                      Command="{Binding AddChildCommand}"
                      CommandParameter="{Binding}"/>
            <MenuItem Header="删除" 
                      Command="{Binding DeleteCommand}"
                      CommandParameter="{Binding}"/>
        </ContextMenu>
    </syncfusion:SfTreeGrid.RecordContextMenu>
</syncfusion:SfTreeGrid>
csharp
public class EmployeeViewModel : INotifyPropertyChanged
{
    public ICommand AddChildCommand { get; set; }
    public ICommand DeleteCommand { get; set; }
    
    public EmployeeViewModel()
    {
        AddChildCommand = new RelayCommand(AddChild);
        DeleteCommand = new RelayCommand(Delete);
    }
    
    private void AddChild(object parameter)
    {
        var parent = parameter as Employee;
        if (parent != null)
        {
            parent.Children.Add(new Employee { /* ... */ });
        }
    }
}

Key Properties

关键属性

Essential Properties

核心属性

PropertyTypeDescription
ItemsSourceIEnumerableData source for the TreeGrid
ChildPropertyNamestringProperty name for child collection
ParentPropertyNamestringProperty name for parent ID (self-relational)
SelfRelationRootValueobjectValue indicating root level nodes
AutoGenerateColumnsboolAuto-generate columns from data source
ColumnsTreeGridColumnsCollection of column definitions
属性类型描述
ItemsSourceIEnumerableTreeGrid的数据源
ChildPropertyNamestring子集合的属性名称
ParentPropertyNamestring父ID的属性名称(自关联)
SelfRelationRootValueobject标识根级别节点的值
AutoGenerateColumnsbool根据数据源自动生成列
ColumnsTreeGridColumns列定义集合

Behavior Properties

行为属性

PropertyTypeDescription
AllowEditingboolEnable/disable cell editing
AllowSortingboolEnable/disable sorting
AllowFilteringboolEnable/disable filtering
FilterLevelFilterLevelFiltering scope (Root, All, Extended)
SelectionModeGridSelectionModeSelection mode (Single, Multiple, Extended)
SelectionUnitGridSelectionUnitSelection unit (Row, Cell, Any)
AutoExpandModeAutoExpandModeAuto-expand behavior (RootNodesExpanded, AllNodesExpanded)
ExpanderPositionExpanderPositionPosition of expand/collapse icon (Start, End)
属性类型描述
AllowEditingbool启用/禁用单元格编辑
AllowSortingbool启用/禁用排序
AllowFilteringbool启用/禁用筛选
FilterLevelFilterLevel筛选范围(Root、All、Extended)
SelectionModeGridSelectionMode选择模式(Single、Multiple、Extended)
SelectionUnitGridSelectionUnit选择单位(Row、Cell、Any)
AutoExpandModeAutoExpandMode自动展开行为(RootNodesExpanded、AllNodesExpanded)
ExpanderPositionExpanderPosition展开/折叠图标位置(Start、End)

Display Properties

显示属性

PropertyTypeDescription
GridLinesVisibilityGridLinesVisibilityGrid lines display (Both, Horizontal, Vertical, None)
ColumnSizerGridLengthUnitTypeColumn auto-sizing strategy
RowHeightdoubleHeight of each row
HeaderRowHeightdoubleHeight of header row
IndentColumnWidthdoubleWidth of indent for each level
属性类型描述
GridLinesVisibilityGridLinesVisibility网格线显示(Both、Horizontal、Vertical、None)
ColumnSizerGridLengthUnitType列自动调整策略
RowHeightdouble每行高度
HeaderRowHeightdouble表头行高度
IndentColumnWidthdouble每个层级的缩进宽度

Common Use Cases

常见用例

1. Employee Hierarchy Management

1. 员工层级管理

Display organizational structure with employees, managers, and departments in expandable tree format.
以可展开树形格式显示组织架构,包含员工、经理及部门信息。

2. File System Browser

2. 文件系统浏览器

Show folders and files in hierarchical structure with load-on-demand for large directory trees.
以层级结构显示文件夹和文件,针对大型目录树使用按需加载。

3. Project Task Management

3. 项目任务管理

Display projects, sub-projects, tasks, and subtasks with status tracking, editing, and conditional styling.
显示项目、子项目、任务及子任务,支持状态跟踪、编辑和条件样式。

4. Bill of Materials (BOM)

4. 物料清单(BOM)

Show product assemblies with components, sub-components, quantities, and costs in hierarchical view.
以层级视图显示产品装配体,包含组件、子组件、数量及成本信息。

5. Category-Product Catalog

5. 分类-产品目录

Display product categories, subcategories, and products with filtering, sorting, and export capabilities.
显示产品分类、子分类及产品,支持筛选、排序和导出功能。

6. Account Hierarchy

6. 账户层级

Financial account trees with parent-child relationships, balance calculations, and drill-down capabilities.
带父子关系的财务账户树,支持余额计算和钻取功能。

7. Multi-Level Approval Workflows

7. 多级审批工作流

Track approval hierarchies with status indicators, conditional styling, and interactive editing.
跟踪审批层级,包含状态指示器、条件样式和交互式编辑。

8. Geographic Data Organization

8. 地理数据组织

Display countries, states, cities in hierarchical format with data visualization and export features.
以层级格式显示国家、州、城市,支持数据可视化和导出功能。

Performance Considerations

性能考量

  • Use Load-On-Demand for datasets with more than 1,000 total nodes
  • Enable Virtualization (enabled by default) for smooth scrolling
  • Avoid complex templates in frequently updated cells
  • Use ItemsSourceChanged event instead of frequent rebinding
  • Batch updates when modifying multiple nodes
  • Disable live updates (LiveNodeUpdateMode) when not needed
  • Optimize FilterLevel choice based on data structure
  • 当总节点数超过1000时,使用按需加载
  • 启用虚拟化(默认已启用)以实现流畅滚动
  • 在频繁更新的单元格中避免复杂模板
  • 频繁重新绑定时,使用ItemsSourceChanged事件替代
  • 修改多个节点时采用批量更新
  • 不需要时禁用实时更新(LiveNodeUpdateMode)
  • 根据数据结构优化FilterLevel选择

Related Skills

相关技能

  • Implementing Syncfusion WPF Components - Parent library skill
  • Implementing Data Grids (Future) - For flat grid data display
  • Implementing Charts - Already available at ../../data-visualization/implementing-charts/
  • 实现Syncfusion WPF组件 - 父库技能
  • 实现数据网格(待发布) - 用于扁平网格数据展示
  • 实现图表 - 已发布于../../data-visualization/implementing-charts/

Support Resources

支持资源


Next Steps: Navigate to the specific reference file above based on your implementation needs. Start with
getting-started.md
for initial setup, then explore data binding, column configuration, and advanced features as needed.

下一步:根据你的实现需求,导航至上述特定参考文件。从
getting-started.md
开始进行初始设置,然后根据需要探索数据绑定、列配置和高级功能。