AvaloniaEdit Binding
AvaloniaEdit 默认不支持Binding操作,因此需要自定义Behavior,将字符串与其`.Document.Text`绑定。 首先创建自定义Behavior: ```c# using System; using Avalonia; using Avalonia.Xaml.Interactivity; using AvaloniaEdit; namespace MatoEditor.Utils; public sealed class AvalonEditBehavior : Behavior<TextEditor> { private TextEditor _textEditor = null; public static readonly StyledProperty<string> TextProperty = AvaloniaProperty.Register<AvalonEditBehavior, 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 > _textEditor.Document.TextLength) { _textEditor.CaretOffset = _textEditor.Document.TextLength; } else { _textEditor.CaretOffset = caretOffset; } } } } ``` 注意官方Wiki给出的代码有部分是: ```c# var caretOffset = _textEditor.CaretOffset; _textEditor.Document.Text = text; _textEditor.CaretOffset = caretOffset; ``` 这个地方肯会导致索引超出文本长度报错,因此要加上一个判断。 然后在axaml文件中使用时加入Behaviors: ```xml <avaloniaEdit:TextEditor Name="TextEditor" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" WordWrap="True"> <Interaction.Behaviors> <utils:AvalonEditBehavior Text="{Binding ContentString, Mode=TwoWay}"/> </Interaction.Behaviors> </avaloniaEdit:TextEditor> ```
创建时间:2024-09-22
|
最后修改:2024-09-22
|
©允许规范转载
酷酷番茄
首页
文章
友链