安裝3個包:
Install-Package Avalonia.AvaloniaEdit
Install-Package AvaloniaEdit.TextMate
Install-Package TextMateSharp.Grammars
在App.xaml的<Application.Styles>下增加:
<StyleInclude Source="avares://AvaloniaEdit/Themes/Fluent/AvaloniaEdit.xaml" />
前臺程式碼:
<Window xmlns="https://github.com/avaloniaui"
...
xmlns:AvaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
...>
...
<AvaloniaEdit:TextEditor Text="Hello AvaloniaEdit!"
ShowLineNumbers="True"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"/>
...
</Window>
後臺程式碼:
//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project.
var _textEditor = this.FindControl<TextEditor>("Editor");
//Here we initialize RegistryOptions with the theme we want to use.
var _registryOptions = new RegistryOptions(ThemeName.DarkPlus);
//Initial setup of TextMate.
var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
//Here we are getting the language by the extension and right after that we are initializing grammar with this language.
//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting!
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id));
參考資料
https://github.com/AvaloniaUI/AvaloniaEdit/?tab=readme-ov-file