enhance: AutoFocusBehaviour will move cursor to the end of contents

This commit is contained in:
leo 2024-04-17 17:13:28 +08:00
parent 1e3711e569
commit 60a4d21ce7

View file

@ -1,4 +1,5 @@
using Avalonia; using Avalonia;
using Avalonia.Controls;
using Avalonia.Input; using Avalonia.Input;
namespace SourceGit.Views namespace SourceGit.Views
@ -6,17 +7,11 @@ namespace SourceGit.Views
public class AutoFocusBehaviour : AvaloniaObject public class AutoFocusBehaviour : AvaloniaObject
{ {
public static readonly AttachedProperty<bool> IsEnabledProperty = public static readonly AttachedProperty<bool> IsEnabledProperty =
AvaloniaProperty.RegisterAttached<AutoFocusBehaviour, InputElement, bool>("IsEnabled", false, false); AvaloniaProperty.RegisterAttached<AutoFocusBehaviour, TextBox, bool>("IsEnabled", false, false);
static AutoFocusBehaviour() static AutoFocusBehaviour()
{ {
IsEnabledProperty.Changed.AddClassHandler<InputElement>((input, e) => IsEnabledProperty.Changed.AddClassHandler<TextBox>(OnIsEnabledChanged);
{
if (input.GetValue(IsEnabledProperty))
{
input.AttachedToVisualTree += (o, _) => (o as InputElement).Focus(NavigationMethod.Directional);
}
});
} }
public static bool GetIsEnabled(AvaloniaObject elem) public static bool GetIsEnabled(AvaloniaObject elem)
@ -28,5 +23,18 @@ namespace SourceGit.Views
{ {
elem.SetValue(IsEnabledProperty, value); elem.SetValue(IsEnabledProperty, value);
} }
private static void OnIsEnabledChanged(TextBox elem, AvaloniaPropertyChangedEventArgs e)
{
if (GetIsEnabled(elem))
{
elem.AttachedToVisualTree += (o, _) =>
{
var text = o as TextBox;
text.Focus(NavigationMethod.Directional);
text.CaretIndex = text.Text == null ? 0 : text.Text.Length;
};
}
}
} }
} }