syncfusion-wpf-syntax-editor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syntax Editor
实现语法编辑器
Guide for implementing Syncfusion® WPF Syntax Editor (EditControl) — an advanced code and text editor control for creating IDE-like editing experiences with syntax highlighting, IntelliSense, find/replace, and comprehensive editing features for multiple programming languages.
本指南介绍如何实现Syncfusion® WPF Syntax Editor(EditControl)——一款高级代码与文本编辑器控件,用于打造类IDE的编辑体验,支持语法高亮、IntelliSense、查找/替换等功能,并兼容多种编程语言。
When to Use This Skill
何时使用该技能
Use this skill when you need to:
- Create code editors with syntax highlighting for C#, VB, XAML, XML, and custom languages
- Build IDE-like applications with advanced text editing capabilities
- Implement IntelliSense with auto-completion and code suggestions
- Add text editors to applications with find/replace, line numbers, and folding
- Support multiple file formats with syntax-aware editing
- Create custom language editors with user-defined syntax rules
- Implement advanced editing features like drag-drop, undo/redo, printing
- Build source code viewers or editors for development tools
- Create log file viewers with syntax highlighting
- Implement configuration file editors with validation
This skill covers the complete Syntax Editor implementation including basic setup, language configuration, editing features, customization, and advanced scenarios.
当你需要以下功能时,可使用该技能:
- 创建代码编辑器:为C#、VB、XAML、XML及自定义语言提供语法高亮
- 构建类IDE应用:具备高级文本编辑能力
- 实现IntelliSense:提供自动补全和代码建议
- 添加文本编辑器:为应用增加查找/替换、行号、代码折叠功能
- 支持多种文件格式:具备语法感知的编辑能力
- 创建自定义语言编辑器:支持用户定义的语法规则
- 实现高级编辑功能:如拖放、撤销/重做、打印
- 构建源代码查看器或编辑器:用于开发工具
- 创建日志文件查看器:支持语法高亮
- 实现配置文件编辑器:具备验证功能
本技能涵盖语法编辑器的完整实现,包括基础设置、语言配置、编辑功能、自定义及高级场景。
Component Overview
组件概述
The Syntax Editor (EditControl) is a high-performance text and code editor control that provides:
- Syntax Highlighting - Built-in support for C#, VB.NET, XAML, XML, and custom languages
- IntelliSense - Auto-completion, parameter info, and code suggestions
- File Operations - Open, save, new file with encoding support
- Advanced Editing - Multi-level undo/redo, clipboard operations, drag-drop
- Find and Replace - Search with regex, match case, whole word
- Text Navigation - Go to line, bookmarks, scroll synchronization
- Line Numbers - Display with customizable appearance
- Code Folding - Expand/collapse code blocks
- Context Menu - Fully customizable with built-in commands
- Status Bar - Line/column position, insert/overwrite mode
- Printing - Print preview and formatted output
- Customization - Fonts, colors, backgrounds, margins
- Read-only Mode - View-only with protection
- Single-line Mode - Use as enhanced TextBox
- Custom Languages - Define your own syntax rules
语法编辑器(EditControl)是一款高性能的文本与代码编辑器控件,提供以下功能:
- 语法高亮:内置支持C#、VB.NET、XAML、XML及自定义语言
- IntelliSense:自动补全、参数信息提示和代码建议
- 文件操作:打开、保存、新建文件,支持编码设置
- 高级编辑:多级撤销/重做、剪贴板操作、拖放
- 查找与替换:支持正则表达式、区分大小写、全字匹配
- 文本导航:跳转到指定行、书签、滚动同步
- 行号显示:可自定义外观
- 代码折叠:展开/折叠代码块
- 上下文菜单:完全可自定义,内置命令
- 状态栏:显示行/列位置、插入/覆盖模式
- 打印功能:打印预览和格式化输出
- 自定义设置:字体、颜色、背景、边距
- 只读模式:仅查看,带保护功能
- 单行模式:用作增强型TextBox
- 自定义语言:定义自己的语法规则
Control Structure
控件结构
EditControl
├── Editor Area - Main text editing surface
│ ├── Line Numbers (optional)
│ ├── Folding Indicators (optional)
│ └── Text Content with Syntax Highlighting
├── Context Menu - Right-click operations
├── Status Bar (optional) - Position and mode info
└── IntelliSense Popup - Auto-completion suggestionsEditControl
├── Editor Area - Main text editing surface
│ ├── Line Numbers (optional)
│ ├── Folding Indicators (optional)
│ └── Text Content with Syntax Highlighting
├── Context Menu - Right-click operations
├── Status Bar (optional) - Position and mode info
└── IntelliSense Popup - Auto-completion suggestionsDocumentation and Navigation Guide
文档与导航指南
Getting Started
入门指南
📄 Read: references/getting-started.md
- Assembly deployment and dependencies
- Adding EditControl via designer, XAML, and C#
- Loading files into the editor
- Basic configuration
- First code editor example
📄 Read: references/overview.md
- Component introduction
- Key features overview
- Real-world scenarios
- Architecture and design
- Performance considerations
📄 Read: references/file-operations.md
- Opening files (Stream, file path)
- Saving files with encoding
- Creating new documents
- File type detection
- Encoding support (UTF-8, ASCII, Unicode)
- Recent files management
📄 阅读: references/getting-started.md
- 程序集部署与依赖
- 通过设计器、XAML和C#添加EditControl
- 将文件加载到编辑器
- 基础配置
- 首个代码编辑器示例
📄 阅读: references/overview.md
- 组件介绍
- 核心功能概述
- 实际应用场景
- 架构与设计
- 性能考量
📄 阅读: references/file-operations.md
- 打开文件(流、文件路径)
- 带编码的文件保存
- 创建新文档
- 文件类型检测
- 编码支持(UTF-8、ASCII、Unicode)
- 最近文件管理
Syntax and Language Support
语法与语言支持
📄 Read: references/syntax-highlighting.md
- Enabling syntax highlighting
- Built-in language support
- Configuring language-specific settings
- Syntax highlighting customization
- Color schemes and themes
- Token-based highlighting
📄 Read: references/supported-languages.md
- C# language support
- Visual Basic support
- XAML language support
- XML language support
- SQL language support
- Language switching at runtime
📄 Read: references/custom-language-support.md
- Creating custom language configurations
- Language base classes (LanguageBase, ProceduralLanguageBase, MarkupLanguageBase)
- Defining lexical states
- Token definitions and patterns
- Custom syntax rules
- Language inheritance
📄 Read: references/intellisense.md
- Enabling IntelliSense features
- Auto-completion lists
- Parameter info tooltips
- Custom IntelliSense data sources
- Triggering IntelliSense programmatically
- IntelliSense appearance customization
📄 阅读: references/syntax-highlighting.md
- 启用语法高亮
- 内置语言支持
- 配置语言特定设置
- 语法高亮自定义
- 配色方案与主题
- 基于标记的高亮
📄 阅读: references/supported-languages.md
- C#语言支持
- Visual Basic支持
- XAML语言支持
- XML语言支持
- SQL语言支持
- 运行时切换语言
📄 阅读: references/custom-language-support.md
- 创建自定义语言配置
- 语言基类(LanguageBase、ProceduralLanguageBase、MarkupLanguageBase)
- 定义词法状态
- 标记定义与模式
- 自定义语法规则
- 语言继承
📄 阅读: references/intellisense.md
- 启用IntelliSense功能
- 自动补全列表
- 参数信息提示框
- 自定义IntelliSense数据源
- 以编程方式触发IntelliSense
- IntelliSense外观自定义
Editing Features
编辑功能
📄 Read: references/editing-text.md
- Basic text editing operations
- Programmatic text manipulation
- Text insertion and deletion
- Document navigation
- Text properties and methods
- Line-based operations
📄 Read: references/edit-commands.md
- Built-in editing commands
- Undo/Redo operations
- Clipboard operations (Cut, Copy, Paste)
- Select All, Delete
- RoutedUICommands usage
- Custom command implementation
- Command bindings
📄 Read: references/selection.md
- Text selection methods
- Selection properties (SelectedText, SelectionStart, SelectionLength)
- Programmatic selection
- Selection appearance customization
- Multi-line selection handling
📄 Read: references/find-and-replace.md
- Find text functionality
- Replace operations
- Find and replace dialog
- Search options (match case, whole word, regex)
- Programmatic search API
- Search result navigation
📄 Read: references/text-navigation.md
- Go to line functionality
- Scroll to position
- Bookmark support
- Keyboard navigation
- Line and column position tracking
- Viewport management
📄 阅读: references/editing-text.md
- 基础文本编辑操作
- 程序化文本操作
- 文本插入与删除
- 文档导航
- 文本属性与方法
- 基于行的操作
📄 阅读: references/edit-commands.md
- 内置编辑命令
- 撤销/重做操作
- 剪贴板操作(剪切、复制、粘贴)
- 全选、删除
- RoutedUICommands使用
- 自定义命令实现
- 命令绑定
📄 阅读: references/selection.md
- 文本选择方法
- 选择属性(SelectedText、SelectionStart、SelectionLength)
- 程序化选择
- 选择外观自定义
- 多行选择处理
📄 阅读: references/find-and-replace.md
- 文本查找功能
- 替换操作
- 查找和替换对话框
- 搜索选项(区分大小写、全字匹配、正则表达式)
- 程序化搜索API
- 搜索结果导航
📄 阅读: references/text-navigation.md
- 跳转到指定行功能
- 滚动到指定位置
- 书签支持
- 键盘导航
- 行与列位置跟踪
- 视口管理
UI Features
UI功能
📄 Read: references/line-numbers.md
- Enabling line numbers
- Line number appearance customization
- Line number margin width
- Line highlighting
- Current line indicator
📄 Read: references/expand-collapse.md
- Code folding regions
- Expand/collapse functionality
- Outlining configuration
- Custom folding rules
- Collapse indicators appearance
- Programmatic expand/collapse
📄 Read: references/context-menu.md
- Default context menu
- Context menu customization
- Adding custom menu items
- Menu command bindings
- Disabling context menu
📄 Read: references/status-bar.md
- Enabling status bar
- Line and column position display
- Insert/Overwrite mode indicator
- Custom status bar content
- Status bar appearance
📄 阅读: references/line-numbers.md
- 启用行号显示
- 行号外观自定义
- 行号边距宽度
- 行高亮
- 当前行指示器
📄 阅读: references/expand-collapse.md
- 代码折叠区域
- 展开/折叠功能
- 大纲配置
- 自定义折叠规则
- 折叠指示器外观
- 程序化展开/折叠
📄 阅读: references/context-menu.md
- 默认上下文菜单
- 上下文菜单自定义
- 添加自定义菜单项
- 菜单命令绑定
- 禁用上下文菜单
📄 阅读: references/status-bar.md
- 启用状态栏
- 行与列位置显示
- 插入/覆盖模式指示器
- 自定义状态栏内容
- 状态栏外观
Customization and Advanced Features
自定义与高级功能
📄 Read: references/customization.md
- Font and color customization
- Background customization
- Line background customization
- Margin and padding settings
- Cursor appearance
- Scroll bar customization
- Visual styles and themes
📄 Read: references/advanced-features.md
- Drag and drop text editing
- Read-only mode
- Single-line mode (enhanced TextBox)
- Printing and print preview
- Split view support
- Performance optimization
- Memory management
📄 阅读: references/customization.md
- 字体与颜色自定义
- 背景自定义
- 行背景自定义
- 边距与内边距设置
- 光标外观
- 滚动条自定义
- 视觉样式与主题
📄 阅读: references/advanced-features.md
- 拖放文本编辑
- 只读模式
- 单行模式(增强型TextBox)
- 打印与打印预览
- 拆分视图支持
- 性能优化
- 内存管理
Quick Start Example
快速入门示例
Basic Code Editor Setup
基础代码编辑器设置
xml
<Window x:Class="CodeEditorApp.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>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Toolbar -->
<ToolBar Grid.Row="0">
<Button Content="Open" Click="OpenFile_Click"/>
<Button Content="Save" Click="SaveFile_Click"/>
<Separator/>
<ComboBox Name="languageComboBox"
SelectionChanged="Language_Changed"
Width="120">
<ComboBoxItem Content="C#" Tag="CSharp"/>
<ComboBoxItem Content="Visual Basic" Tag="VB"/>
<ComboBoxItem Content="XAML" Tag="XAML"/>
<ComboBoxItem Content="XML" Tag="XML"/>
</ComboBox>
</ToolBar>
<!-- Syntax Editor -->
<syncfusion:EditControl Name="editControl"
Grid.Row="1"
DocumentLanguage="CSharp"
ShowLineNumber="True"
EnableOutlining="True"
EnableIntellisense="True"
Background="White"
FontSize="12"
FontFamily="Consolas"/>
</Grid>
</Window>csharp
using Syncfusion.Windows.Edit;
using Microsoft.Win32;
using System.IO;
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Set initial language
editControl.DocumentLanguage = Languages.CSharp;
languageComboBox.SelectedIndex = 0;
}
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog
{
Filter = "C# Files (*.cs)|*.cs|VB Files (*.vb)|*.vb|XAML Files (*.xaml)|*.xaml|All Files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
editControl.Load(dialog.FileName);
// Auto-detect language from extension
string ext = Path.GetExtension(dialog.FileName).ToLower();
switch (ext)
{
case ".cs":
editControl.DocumentLanguage = Languages.CSharp;
break;
case ".vb":
editControl.DocumentLanguage = Languages.VB;
break;
case ".xaml":
editControl.DocumentLanguage = Languages.XAML;
break;
case ".xml":
editControl.DocumentLanguage = Languages.XML;
break;
}
}
}
private void SaveFile_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog
{
Filter = "C# Files (*.cs)|*.cs|VB Files (*.vb)|*.vb|XAML Files (*.xaml)|*.xaml|All Files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
editControl.Save(dialog.FileName);
}
}
private void Language_Changed(object sender, SelectionChangedEventArgs e)
{
if (editControl == null) return;
var selected = (ComboBoxItem)languageComboBox.SelectedItem;
string language = selected.Tag.ToString();
switch (language)
{
case "CSharp":
editControl.DocumentLanguage = Languages.CSharp;
break;
case "VB":
editControl.DocumentLanguage = Languages.VB;
break;
case "XAML":
editControl.DocumentLanguage = Languages.XAML;
break;
case "XML":
editControl.DocumentLanguage = Languages.XML;
break;
}
}
}xml
<Window x:Class="CodeEditorApp.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>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Toolbar -->
<ToolBar Grid.Row="0">
<Button Content="Open" Click="OpenFile_Click"/>
<Button Content="Save" Click="SaveFile_Click"/>
<Separator/>
<ComboBox Name="languageComboBox"
SelectionChanged="Language_Changed"
Width="120">
<ComboBoxItem Content="C#" Tag="CSharp"/>
<ComboBoxItem Content="Visual Basic" Tag="VB"/>
<ComboBoxItem Content="XAML" Tag="XAML"/>
<ComboBoxItem Content="XML" Tag="XML"/>
</ComboBox>
</ToolBar>
<!-- Syntax Editor -->
<syncfusion:EditControl Name="editControl"
Grid.Row="1"
DocumentLanguage="CSharp"
ShowLineNumber="True"
EnableOutlining="True"
EnableIntellisense="True"
Background="White"
FontSize="12"
FontFamily="Consolas"/>
</Grid>
</Window>csharp
using Syncfusion.Windows.Edit;
using Microsoft.Win32;
using System.IO;
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Set initial language
editControl.DocumentLanguage = Languages.CSharp;
languageComboBox.SelectedIndex = 0;
}
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog
{
Filter = "C# Files (*.cs)|*.cs|VB Files (*.vb)|*.vb|XAML Files (*.xaml)|*.xaml|All Files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
editControl.Load(dialog.FileName);
// Auto-detect language from extension
string ext = Path.GetExtension(dialog.FileName).ToLower();
switch (ext)
{
case ".cs":
editControl.DocumentLanguage = Languages.CSharp;
break;
case ".vb":
editControl.DocumentLanguage = Languages.VB;
break;
case ".xaml":
editControl.DocumentLanguage = Languages.XAML;
break;
case ".xml":
editControl.DocumentLanguage = Languages.XML;
break;
}
}
}
private void SaveFile_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog
{
Filter = "C# Files (*.cs)|*.cs|VB Files (*.vb)|*.vb|XAML Files (*.xaml)|*.xaml|All Files (*.*)|*.*"
};
if (dialog.ShowDialog() == true)
{
editControl.Save(dialog.FileName);
}
}
private void Language_Changed(object sender, SelectionChangedEventArgs e)
{
if (editControl == null) return;
var selected = (ComboBoxItem)languageComboBox.SelectedItem;
string language = selected.Tag.ToString();
switch (language)
{
case "CSharp":
editControl.DocumentLanguage = Languages.CSharp;
break;
case "VB":
editControl.DocumentLanguage = Languages.VB;
break;
case "XAML":
editControl.DocumentLanguage = Languages.XAML;
break;
case "XML":
editControl.DocumentLanguage = Languages.XML;
break;
}
}
}Common Patterns
常见模式
Pattern 1: Load and Save Files with Encoding
模式1:带编码的文件加载与保存
csharp
// Load file with specific encoding
editControl.Load("path/to/file.cs", Encoding.UTF8);
// Save with encoding
editControl.Save("path/to/output.cs", Encoding.UTF8);
// Load from stream
using (FileStream stream = new FileStream("file.cs", FileMode.Open))
{
editControl.Load(stream, Encoding.UTF8);
}
// Save to stream
using (FileStream stream = new FileStream("output.cs", FileMode.Create))
{
editControl.Save(stream, Encoding.UTF8);
}csharp
// Load file with specific encoding
editControl.Load("path/to/file.cs", Encoding.UTF8);
// Save with encoding
editControl.Save("path/to/output.cs", Encoding.UTF8);
// Load from stream
using (FileStream stream = new FileStream("file.cs", FileMode.Open))
{
editControl.Load(stream, Encoding.UTF8);
}
// Save to stream
using (FileStream stream = new FileStream("output.cs", FileMode.Create))
{
editControl.Save(stream, Encoding.UTF8);
}Pattern 2: Custom IntelliSense with Auto-Completion
模式2:带自动补全的自定义IntelliSense
csharp
// Enable IntelliSense
editControl.EnableIntellisense = true;
editControl.IntellisenseMode = IntellisenseMode.Automatic;
// Add custom IntelliSense items
editControl.IntellisenseItems.Add(new IntellisenseItem
{
Text = "CustomMethod",
Description = "My custom method",
ImageSource = myIcon
});
// Handle IntellisenseOpening event
editControl.IntellisenseOpening += (s, e) =>
{
// Add context-specific items
if (editControl.Text.Contains("using System"))
{
e.IntellisenseItems.Add(new IntellisenseItem
{
Text = "Console",
Description = "System.Console class"
});
}
};csharp
// Enable IntelliSense
editControl.EnableIntellisense = true;
editControl.IntellisenseMode = IntellisenseMode.Automatic;
// Add custom IntelliSense items
editControl.IntellisenseItems.Add(new IntellisenseItem
{
Text = "CustomMethod",
Description = "My custom method",
ImageSource = myIcon
});
// Handle IntellisenseOpening event
editControl.IntellisenseOpening += (s, e) =>
{
// Add context-specific items
if (editControl.Text.Contains("using System"))
{
e.IntellisenseItems.Add(new IntellisenseItem
{
Text = "Console",
Description = "System.Console class"
});
}
};Pattern 3: Find and Replace with Regex
模式3:带正则表达式的查找与替换
csharp
// Simple find
FindResult result = editControl.FindText("SearchTerm",
FindOptions.MatchCase | FindOptions.WholeWord);
if (result != null)
{
Console.WriteLine($"Found at line {result.LineNumber}");
}
// Find with regex
FindResult regexResult = editControl.FindText(@"\d{3}-\d{4}",
FindOptions.UseRegularExpressions);
// Replace all occurrences
int replacedCount = editControl.ReplaceAll("oldText", "newText",
FindOptions.MatchCase);
// Replace with confirmation
while (editControl.FindNext("oldText", FindOptions.None))
{
var dialogResult = MessageBox.Show("Replace this occurrence?",
"Confirm", MessageBoxButton.YesNoCancel);
if (dialogResult == MessageBoxResult.Yes)
editControl.SelectedText = "newText";
else if (dialogResult == MessageBoxResult.Cancel)
break;
}csharp
// Simple find
FindResult result = editControl.FindText("SearchTerm",
FindOptions.MatchCase | FindOptions.WholeWord);
if (result != null)
{
Console.WriteLine($"Found at line {result.LineNumber}");
}
// Find with regex
FindResult regexResult = editControl.FindText(@"\d{3}-\d{4}",
FindOptions.UseRegularExpressions);
// Replace all occurrences
int replacedCount = editControl.ReplaceAll("oldText", "newText",
FindOptions.MatchCase);
// Replace with confirmation
while (editControl.FindNext("oldText", FindOptions.None))
{
var dialogResult = MessageBox.Show("Replace this occurrence?",
"Confirm", MessageBoxButton.YesNoCancel);
if (dialogResult == MessageBoxResult.Yes)
editControl.SelectedText = "newText";
else if (dialogResult == MessageBoxResult.Cancel)
break;
}Pattern 4: Custom Language Definition
模式4:自定义语言定义
csharp
// Create custom language
public class CustomLanguage : ProceduralLanguageBase
{
public CustomLanguage(EditControl control) : base(control)
{
Name = "MyLanguage";
FileExtension = ".mylang";
// Define keywords
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.Keyword,
Lexem = "function|class|if|else|while|for",
IsRegex = true,
ForeColor = Colors.Blue
});
// Define strings
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.String,
Lexem = "\".*?\"",
IsRegex = true,
ForeColor = Colors.Brown
});
// Define comments
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.Comment,
Lexem = "//.*",
IsRegex = true,
ForeColor = Colors.Green
});
}
}
// Apply custom language
editControl.DocumentLanguage = new CustomLanguage(editControl);csharp
// Create custom language
public class CustomLanguage : ProceduralLanguageBase
{
public CustomLanguage(EditControl control) : base(control)
{
Name = "MyLanguage";
FileExtension = ".mylang";
// Define keywords
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.Keyword,
Lexem = "function|class|if|else|while|for",
IsRegex = true,
ForeColor = Colors.Blue
});
// Define strings
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.String,
Lexem = "\".*?\"",
IsRegex = true,
ForeColor = Colors.Brown
});
// Define comments
Lexems.Add(new LexemDefinition
{
Type = EditTokenType.Comment,
Lexem = "//.*",
IsRegex = true,
ForeColor = Colors.Green
});
}
}
// Apply custom language
editControl.DocumentLanguage = new CustomLanguage(editControl);Pattern 5: Code Folding and Outlining
模式5:代码折叠与大纲
csharp
// Enable outlining
editControl.EnableOutlining = true;
// Collapse all regions
editControl.CollapseAll();
// Expand all regions
editControl.ExpandAll();
// Toggle specific region
editControl.ToggleOutlining(lineNumber);
// Programmatically add folding region
editControl.AddFoldingRegion(startLine, endLine, "Region Name");
// Handle outlining events
editControl.OutlineCollapsed += (s, e) =>
{
Console.WriteLine($"Collapsed region at line {e.StartLine}");
};csharp
// Enable outlining
editControl.EnableOutlining = true;
// Collapse all regions
editControl.CollapseAll();
// Expand all regions
editControl.ExpandAll();
// Toggle specific region
editControl.ToggleOutlining(lineNumber);
// Programmatically add folding region
editControl.AddFoldingRegion(startLine, endLine, "Region Name");
// Handle outlining events
editControl.OutlineCollapsed += (s, e) =>
{
Console.WriteLine($"Collapsed region at line {e.StartLine}");
};Key Properties
核心属性
Core Properties
核心属性
| Property | Type | Description |
|---|---|---|
| Text | string | Gets/sets the entire text content |
| DocumentLanguage | ILanguage | Current language for syntax highlighting |
| ShowLineNumber | bool | Shows/hides line numbers |
| EnableIntellisense | bool | Enables IntelliSense features |
| EnableOutlining | bool | Enables code folding |
| IsReadOnly | bool | Makes editor read-only |
| SingleLineMode | bool | Uses editor as single-line TextBox |
| Property | Type | Description |
|---|---|---|
| Text | string | 获取/设置整个文本内容 |
| DocumentLanguage | ILanguage | 当前用于语法高亮的语言 |
| ShowLineNumber | bool | 显示/隐藏行号 |
| EnableIntellisense | bool | 启用IntelliSense功能 |
| EnableOutlining | bool | 启用代码折叠 |
| IsReadOnly | bool | 将编辑器设置为只读 |
| SingleLineMode | bool | 将编辑器用作单行TextBox |
Selection Properties
选择属性
| Property | Type | Description |
|---|---|---|
| SelectedText | string | Gets/sets currently selected text |
| SelectionStart | int | Selection start position |
| SelectionLength | int | Length of selection |
| CurrentLine | int | Current cursor line number |
| CurrentColumn | int | Current cursor column position |
| Property | Type | Description |
|---|---|---|
| SelectedText | string | 获取/设置当前选中的文本 |
| SelectionStart | int | 选择起始位置 |
| SelectionLength | int | 选择长度 |
| CurrentLine | int | 当前光标所在行号 |
| CurrentColumn | int | 当前光标所在列号 |
Appearance Properties
外观属性
| Property | Type | Description |
|---|---|---|
| FontFamily | FontFamily | Editor font |
| FontSize | double | Editor font size |
| Background | Brush | Editor background |
| Foreground | Brush | Default text color |
| LineNumberForeground | Brush | Line number color |
| SelectionBrush | Brush | Selection background color |
| Property | Type | Description |
|---|---|---|
| FontFamily | FontFamily | 编辑器字体 |
| FontSize | double | 编辑器字体大小 |
| Background | Brush | 编辑器背景 |
| Foreground | Brush | 默认文本颜色 |
| LineNumberForeground | Brush | 行号颜色 |
| SelectionBrush | Brush | 选中文本的背景色 |
Behavior Properties
行为属性
| Property | Type | Description |
|---|---|---|
| AllowDragDrop | bool | Enables text drag-drop |
| WordWrap | bool | Enables word wrapping |
| TabSize | int | Tab character width |
| UseSpacesInsteadOfTabs | bool | Converts tabs to spaces |
| AutoIndent | bool | Automatic indentation |
| Property | Type | Description |
|---|---|---|
| AllowDragDrop | bool | 启用文本拖放 |
| WordWrap | bool | 启用自动换行 |
| TabSize | int | 制表符宽度 |
| UseSpacesInsteadOfTabs | bool | 将制表符转换为空格 |
| AutoIndent | bool | 自动缩进 |
Events
事件
| Event | Description |
|---|---|
| TextChanged | Fired when text content changes |
| SelectionChanged | Fired when selection changes |
| DocumentLanguageChanged | Fired when language changes |
| IntellisenseOpening | Fired before showing IntelliSense popup |
| OutlineCollapsed | Fired when outline region collapses |
| OutlineExpanded | Fired when outline region expands |
| Event | Description |
|---|---|
| TextChanged | 文本内容更改时触发 |
| SelectionChanged | 选中内容更改时触发 |
| DocumentLanguageChanged | 语言更改时触发 |
| IntellisenseOpening | 显示IntelliSense弹出框前触发 |
| OutlineCollapsed | 大纲区域折叠时触发 |
| OutlineExpanded | 大纲区域展开时触发 |
Common Use Cases
常见使用场景
1. Source Code Editor for IDEs
1. IDE源代码编辑器
Build development environments with syntax highlighting, IntelliSense, and debugging integration.
构建带语法高亮、IntelliSense和调试集成的开发环境。
2. Configuration File Editor
2. 配置文件编辑器
Create editors for XML, JSON, YAML configuration files with validation and auto-completion.
创建用于XML、JSON、YAML配置文件的编辑器,支持验证和自动补全。
3. Log File Viewer
3. 日志文件查看器
Display and analyze log files with syntax highlighting for different log levels and patterns.
显示和分析日志文件,为不同日志级别和模式提供语法高亮。
4. SQL Query Editor
4. SQL查询编辑器
Build database query tools with SQL syntax highlighting and query execution.
构建数据库查询工具,支持SQL语法高亮和查询执行。
5. Script Editor
5. 脚本编辑器
Create scripting environments for PowerShell, Python, or custom scripting languages.
创建PowerShell、Python或自定义脚本语言的脚本环境。
6. Markdown Editor
6. Markdown编辑器
Implement markdown editors with live preview and syntax highlighting.
实现带实时预览和语法高亮的Markdown编辑器。
7. Template Editor
7. 模板编辑器
Build template editing tools for code generation or document templates.
构建用于代码生成或文档模板的模板编辑工具。
8. Educational Coding Tools
8. 教育类编程工具
Create learning applications with code highlighting and interactive examples.
创建带代码高亮和交互式示例的学习应用。
Best Practices
最佳实践
-
Language Selection
- Set based on file extension
DocumentLanguage - Provide UI for manual language switching
- Support language-specific configurations
- Set
-
Performance
- Use /
BeginUpdate()for bulk text operationsEndUpdate() - Enable virtualization for large files
- Consider read-only mode for view-only scenarios
- Use
-
User Experience
- Always show line numbers for code editing
- Enable IntelliSense for better productivity
- Provide find/replace functionality
- Support standard keyboard shortcuts
-
File Operations
- Always specify encoding when loading/saving
- Handle encoding detection for existing files
- Implement auto-save or prompt for unsaved changes
-
Customization
- Use themes for consistent appearance
- Allow users to customize fonts and colors
- Provide syntax highlighting customization options
-
Accessibility
- Support keyboard navigation
- Provide screen reader compatibility
- Ensure sufficient color contrast
-
语言选择
- 根据文件扩展名设置
DocumentLanguage - 提供手动切换语言的UI
- 支持特定语言的配置
- 根据文件扩展名设置
-
性能优化
- 批量文本操作时使用/
BeginUpdate()EndUpdate() - 大文件启用虚拟化
- 仅查看场景使用只读模式
- 批量文本操作时使用
-
用户体验
- 代码编辑时始终显示行号
- 启用IntelliSense提升生产力
- 提供查找/替换功能
- 支持标准键盘快捷键
-
文件操作
- 加载/保存时始终指定编码
- 处理现有文件的编码检测
- 实现自动保存或提示未保存更改
-
自定义设置
- 使用主题保持外观一致性
- 允许用户自定义字体和颜色
- 提供语法高亮自定义选项
-
可访问性
- 支持键盘导航
- 提供屏幕阅读器兼容性
- 确保足够的颜色对比度
Troubleshooting
故障排除
Syntax Highlighting Not Working
语法高亮不工作
- Verify is set correctly
DocumentLanguage - Check if language is properly initialized
- Ensure custom language definitions are complete
- 验证是否正确设置
DocumentLanguage - 检查语言是否正确初始化
- 确保自定义语言定义完整
IntelliSense Not Appearing
IntelliSense不显示
- Verify is
EnableIntellisensetrue - Check setting
IntellisenseMode - Ensure IntelliSense items are populated
- 验证是否设为
EnableIntellisensetrue - 检查设置
IntellisenseMode - 确保IntelliSense项已填充
Performance Issues with Large Files
大文件性能问题
- Enable virtualization
- Use /
BeginUpdate()for batch operationsEndUpdate() - Consider pagination or lazy loading for very large files
- 启用虚拟化
- 批量操作使用/
BeginUpdate()EndUpdate() - 超大文件考虑分页或懒加载
Line Numbers Not Showing
行号不显示
- Verify is
ShowLineNumbertrue - Check if line number margin has sufficient width
- Ensure visual style doesn't hide line numbers
Next Steps: Navigate to specific reference documents based on your implementation needs. Start with getting-started.md for initial setup, then explore syntax highlighting, IntelliSense, and editing features as needed.
- 验证是否设为
ShowLineNumbertrue - 检查行号边距是否有足够宽度
- 确保视觉样式未隐藏行号
下一步: 根据你的实现需求,导航到特定的参考文档。从getting-started.md开始进行初始设置,然后根据需要探索语法高亮、IntelliSense和编辑功能。