You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
2.3 KiB
65 lines
2.3 KiB
using Avalonia;
|
|
using Avalonia.Data;
|
|
using AvaloniaEdit;
|
|
using AvaloniaEdit.Document;
|
|
|
|
namespace MyAvaloniaApp.Attached;
|
|
|
|
/// <summary>
|
|
/// 为 <see cref="TextEditor"/> 提供可绑定的 <see cref="TextDocument"/> 附加属性,
|
|
/// 便于在 MVVM 模式下直接绑定到 ViewModel。
|
|
/// </summary>
|
|
public static class TextEditorAssist
|
|
{
|
|
public static readonly AttachedProperty<TextDocument?> DocumentProperty =
|
|
AvaloniaProperty.RegisterAttached<TextEditor, TextDocument?>(
|
|
"Document",
|
|
typeof(TextEditorAssist),
|
|
defaultBindingMode: BindingMode.TwoWay);
|
|
|
|
private static readonly AttachedProperty<bool> IsInternalUpdateProperty =
|
|
AvaloniaProperty.RegisterAttached<TextEditor, bool>(
|
|
"IsInternalUpdate",
|
|
typeof(TextEditorAssist));
|
|
|
|
static TextEditorAssist()
|
|
{
|
|
DocumentProperty.Changed.AddClassHandler<TextEditor>(OnDocumentPropertyChanged);
|
|
TextEditor.DocumentProperty.Changed.AddClassHandler<TextEditor>(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);
|
|
}
|
|
}
|
|
}
|
|
|
|
|