|
| 1 | +using System.Reactive.Disposables; |
| 2 | +using Avalonia.Input; |
| 3 | +using Avalonia.Interactivity; |
| 4 | +using Avalonia.Xaml.Interactivity; |
| 5 | + |
| 6 | +namespace Avalonia.Xaml.Interactions.Custom; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// |
| 10 | +/// </summary> |
| 11 | +public class TextInputTrigger : RoutedEventTriggerBase |
| 12 | +{ |
| 13 | + static TextInputTrigger() |
| 14 | + { |
| 15 | + EventRoutingStrategyProperty.OverrideMetadata<TextInputTrigger>( |
| 16 | + new StyledPropertyMetadata<RoutingStrategies>( |
| 17 | + defaultValue: RoutingStrategies.Tunnel | RoutingStrategies.Bubble)); |
| 18 | + } |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// |
| 22 | + /// </summary> |
| 23 | + public static readonly StyledProperty<string?> TextProperty = |
| 24 | + AvaloniaProperty.Register<KeyDownTrigger, string?>(nameof(Text)); |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// |
| 28 | + /// </summary> |
| 29 | + public string? Text |
| 30 | + { |
| 31 | + get => GetValue(TextProperty); |
| 32 | + set => SetValue(TextProperty, value); |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// |
| 37 | + /// </summary> |
| 38 | + /// <param name="disposables"></param> |
| 39 | + protected override void OnAttached(CompositeDisposable disposables) |
| 40 | + { |
| 41 | + if (AssociatedObject is InputElement element) |
| 42 | + { |
| 43 | + var disposable = element.AddDisposableHandler( |
| 44 | + InputElement.TextInputEvent, |
| 45 | + OnTextInput, |
| 46 | + EventRoutingStrategy); |
| 47 | + disposables.Add(disposable); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private void OnTextInput(object? sender, TextInputEventArgs e) |
| 52 | + { |
| 53 | + if (!IsEnabled) |
| 54 | + { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + var text = Text; |
| 59 | + var haveText = text is not null && e.Text == text; |
| 60 | + |
| 61 | + if (text is null || haveText) |
| 62 | + { |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + e.Handled = MarkAsHandled; |
| 67 | + Interaction.ExecuteActions(AssociatedObject, Actions, e); |
| 68 | + } |
| 69 | +} |
0 commit comments