我使用 Daniel Grünwald 的 BraceFoldingStrategy:
public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
{
List<NewFolding> newFoldings = new List<NewFolding>();
Stack<int> startOffsets = new Stack<int>();
int lastNewLineOffset = 0;
char openingBrace = this.OpeningBrace;
char closingBrace = this.ClosingBrace;
for (int i = 0; i < document.TextLength; i++) {
char c = document.GetCharAt(i);
if (c == openingBrace) {
startOffsets.Push(i);
} else if (c == closingBrace && startOffsets.Count > 0) {
int startOffset = startOffsets.Pop();
// don't fold if opening and closing brace are on the same line
if (startOffset < lastNewLineOffset) {
newFoldings.Add(new NewFolding(startOffset, i + 1));
}
} else if (c == '\n' || c == '\r') {
lastNewLineOffset = i + 1;
}
}
newFoldings.Sort((a,b) => a.StartOffset.CompareTo(b.StartOffset));
return newFoldings;
}
这按预期工作,但还有一个问题
最后一个大括号上总是有一个最后一个 - 图标。我试图删除它,但是当我查看列表 newFoldings 时,我可以看到那里只有 3 个折叠。那么第四个是从哪里来的呢?
编辑
根据 Daniel Grünwald 的说法,问题在于我必须使用不同的折叠管理器。但是,我在设置第二个 FoldingManager 的初始化代码中找不到任何语句。也许有任何提示?
private void textEditor_Loaded(object sender, RoutedEventArgs e)
{
LoadSourceCode();
textEditor.Background = Brushes.Green;
textEditor.IsReadOnly = true;
textEditor.ShowLineNumbers = true;
using (Stream s = this.GetType().Assembly.GetManifestResourceStream("Prototype_Concept_2.View.Layouts.CustomHighlighting.xshd"))
{
using (XmlTextReader reader = new XmlTextReader(s))
{
textEditor.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
}
}
(textEditor.TextArea as IScrollInfo).ScrollOwner.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
(textEditor.TextArea as IScrollInfo).ScrollOwner.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
FoldingManager foldingManager = FoldingManager.Install(textEditor.TextArea);
BraceFoldingStrategy foldingStrategy = new BraceFoldingStrategy();
foldingStrategy.UpdateFoldings(foldingManager, textEditor.Document);
TextArea txt = textEditor.TextArea;
ObservableCollection<UIElement> margins = txt.LeftMargins;
foreach (UIElement margin in margins)
{
if ((margin as FoldingMargin) != null)
{
Contacts.AddPreviewContactDownHandler(margin as FoldingMargin, OnDown);
}
}
Main.Children.Remove(textEditor);
ScrollHost.Width = textEditor.Width;
ScrollHost.Height = textEditor.Height;
ScrollHost.Content = textEditor;
textEditor.Background = Brushes.Transparent;
ScrollHost.Background = Brushes.Transparent;
}
编辑 2
我检查了当前安装的 FoldingManager 有 3 个折叠,但我仍然不知道第四个折叠定义在哪里。