Skip to content

Commit 60a4d21

Browse files
committed
enhance: AutoFocusBehaviour will move cursor to the end of contents
1 parent 1e3711e commit 60a4d21

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

src/Views/AutoFocusBehaviour.cs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,17 @@
11
using Avalonia;
2+
using Avalonia.Controls;
23
using Avalonia.Input;
34

45
namespace SourceGit.Views
56
{
67
public class AutoFocusBehaviour : AvaloniaObject
78
{
89
public static readonly AttachedProperty<bool> IsEnabledProperty =
9-
AvaloniaProperty.RegisterAttached<AutoFocusBehaviour, InputElement, bool>("IsEnabled", false, false);
10+
AvaloniaProperty.RegisterAttached<AutoFocusBehaviour, TextBox, bool>("IsEnabled", false, false);
1011

1112
static AutoFocusBehaviour()
1213
{
13-
IsEnabledProperty.Changed.AddClassHandler<InputElement>((input, e) =>
14-
{
15-
if (input.GetValue(IsEnabledProperty))
16-
{
17-
input.AttachedToVisualTree += (o, _) => (o as InputElement).Focus(NavigationMethod.Directional);
18-
}
19-
});
14+
IsEnabledProperty.Changed.AddClassHandler<TextBox>(OnIsEnabledChanged);
2015
}
2116

2217
public static bool GetIsEnabled(AvaloniaObject elem)
@@ -28,5 +23,18 @@ public static void SetIsEnabled(AvaloniaObject elem, bool value)
2823
{
2924
elem.SetValue(IsEnabledProperty, value);
3025
}
26+
27+
private static void OnIsEnabledChanged(TextBox elem, AvaloniaPropertyChangedEventArgs e)
28+
{
29+
if (GetIsEnabled(elem))
30+
{
31+
elem.AttachedToVisualTree += (o, _) =>
32+
{
33+
var text = o as TextBox;
34+
text.Focus(NavigationMethod.Directional);
35+
text.CaretIndex = text.Text == null ? 0 : text.Text.Length;
36+
};
37+
}
38+
}
3139
}
3240
}

0 commit comments

Comments
 (0)