AvalonEdit更改代码中的语法高亮显示

本文关键字:语法 高亮 显示 代码 AvalonEdit | 更新日期: 2023-09-27 18:10:24

我想在我的代码中改变AvalonEdit的语法高亮。

XAML:

 <avalonEdit:TextEditor Name="textEditor" SyntaxHighlighting="{Binding syntaxHighlighting}" />
c#:

public string syntaxHighlighting { get; set; }
public MainWindow()
{
     InitializeComponent();
     syntaxHighlighting = "C#";
     DataContext = this;
}

但是语法突出显示没有改变。我做错了什么?我的问题有更好的解决办法吗?

AvalonEdit更改代码中的语法高亮显示

ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.GetDefinition("C#");

给你:

ICSharpCode.AvalonEdit.TextEditor textEditor = new ICSharpCode.AvalonEdit.TextEditor();
textEditor.ShowLineNumbers = true;
string dir = @"C:'Program Files'MyFolder'";
#if DEBUG
dir = @"C:'Dev'Sandbox'SharpDevelop-master'src'Libraries'AvalonEdit'ICSharpCode.AvalonEdit'Highlighting'Resources'";
#endif
Stream xshd_stream = File.OpenRead(dir + "CSharp-Mode.xshd");
XmlTextReader xshd_reader = new XmlTextReader(xshd_stream);
textEditor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(xshd_reader, ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
xshd_reader.Close();
xshd_stream.Close();
编辑:

自ICSharp

。TextEditor抛出AccessViolations在WinForms,我使用AvalonEdit在WinForms:

ElementHost host = new ElementHost();
host.Size = new Size(200, 100);
host.Location = new Point(100, 100);
host.Child = textEditor;
this.Controls.Add(host);

如果你想绑定到一个字符串,你可以定义一个IValueConverter来包装内置的HighlightingDefinitionTypeConverter:

using System;
using System.Globalization;
using System.Windows.Data;
using ICSharpCode.AvalonEdit.Highlighting;
public class HighlightingDefinitionConverter : IValueConverter
{
    private static readonly HighlightingDefinitionTypeConverter Converter = new HighlightingDefinitionTypeConverter();
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Converter.ConvertFrom(value);
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Converter.ConvertToString(value);
    }
}

然后,只需将转换器添加到绑定中:

<avalonEdit:TextEditor Name="textEditor" SyntaxHighlighting="{Binding syntaxHighlighting, Converter={StaticResource HighlightingDefinitionConverter}}" />

直接使用TypeConverter

var typeConverter = new HighlightingDefinitionTypeConverter();
var xmlSyntaxHighlighter = (IHighlightingDefinition)typeConverter.ConvertFrom("XML");
var csSyntaxHighlighter = (IHighlightingDefinition)typeConverter.ConvertFrom("C#");
CSharpEditor.SyntaxHighlighting = csSyntaxHighlighter;
XmlEditor.SyntaxHighlighting = xmlSyntaxHighlighter;

syntaxhighlight不是字符串!您的代码可能无法编译!注意,这里XAML中的syntaxhighlight使用标记扩展,它实例化了syntaxhighlight的实例,而不是字符串。

private void OnTabLoaded(object sender, RoutedEventArgs e)
{
   textEditor.SyntaxHighlighting = HighlightingLoader.Load(..., HighlightingManager.Instance);
   textEditor.SyntaxHighlighting.MainRuleSet=...
}

进入sharpdevelop下载源代码