-
Notifications
You must be signed in to change notification settings - Fork 1
/
DocumentTextBindingBehavior.cs
64 lines (54 loc) · 1.61 KB
/
DocumentTextBindingBehavior.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using Avalonia;
using Avalonia.Xaml.Interactivity;
using AvaloniaEdit;
using AvaloniaEdit.Utils;
namespace SharpFM.Behaviors;
public class DocumentTextBindingBehavior : Behavior<TextEditor>
{
private TextEditor _textEditor = null!;
public static readonly StyledProperty<string> TextProperty =
AvaloniaProperty.Register<DocumentTextBindingBehavior, string>(nameof(Text));
public string Text
{
get => GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is TextEditor textEditor)
{
_textEditor = textEditor;
_textEditor.TextChanged += TextChanged;
this.GetObservable(TextProperty).Subscribe(TextPropertyChanged);
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (_textEditor != null)
{
_textEditor.TextChanged -= TextChanged;
}
}
private void TextChanged(object? sender, EventArgs eventArgs)
{
if (_textEditor != null && _textEditor.Document != null)
{
Text = _textEditor.Document.Text;
}
}
private void TextPropertyChanged(string text)
{
if (_textEditor != null && _textEditor.Document != null && text != null)
{
var caretOffset = _textEditor.CaretOffset;
_textEditor.Document.Text = text;
if (caretOffset <= text.Length)
{
_textEditor.CaretOffset = caretOffset;
}
}
}
}