using Avalonia; using Avalonia.Data; using AvaloniaEdit; using AvaloniaEdit.Document; namespace MyAvaloniaApp.Attached; /// /// 为 提供可绑定的 附加属性, /// 便于在 MVVM 模式下直接绑定到 ViewModel。 /// public static class TextEditorAssist { public static readonly AttachedProperty DocumentProperty = AvaloniaProperty.RegisterAttached( "Document", typeof(TextEditorAssist), defaultBindingMode: BindingMode.TwoWay); private static readonly AttachedProperty IsInternalUpdateProperty = AvaloniaProperty.RegisterAttached( "IsInternalUpdate", typeof(TextEditorAssist)); static TextEditorAssist() { DocumentProperty.Changed.AddClassHandler(OnDocumentPropertyChanged); TextEditor.DocumentProperty.Changed.AddClassHandler(OnEditorDocumentChanged); } public static void SetDocument(TextEditor editor, TextDocument? value) => editor.SetValue(DocumentProperty, value); public static TextDocument? GetDocument(TextEditor editor) => editor.GetValue(DocumentProperty); private static void OnDocumentPropertyChanged(TextEditor editor, AvaloniaPropertyChangedEventArgs change) { if (editor.GetValue(IsInternalUpdateProperty)) return; var document = change.NewValue as TextDocument; if (!ReferenceEquals(editor.Document, document)) { editor.SetValue(IsInternalUpdateProperty, true); editor.Document = document; editor.SetValue(IsInternalUpdateProperty, false); } } private static void OnEditorDocumentChanged(TextEditor editor, AvaloniaPropertyChangedEventArgs change) { if (editor.GetValue(IsInternalUpdateProperty)) return; var document = change.NewValue as TextDocument; if (!ReferenceEquals(editor.GetValue(DocumentProperty), document)) { editor.SetValue(IsInternalUpdateProperty, true); editor.SetValue(DocumentProperty, document); editor.SetValue(IsInternalUpdateProperty, false); } } }