Add ability to cancel focus change by emmauss · Pull Request #18373 · AvaloniaUI/Avalonia (original) (raw)

What does the pull request do?

Adds the following api;

public class FocusChangingEventArgs : RoutedEventArgs { ///

/// Gets or sets the element that focus has moved to. /// public IInputElement? NewFocusedElement { get; }

    /// <summary>
    /// Gets or sets the element that previously had focus.
    /// </summary>
    public IInputElement? OldFocusedElement { get; }

    /// <summary>
    /// Gets or sets a value indicating how the change in focus occurred.
    /// </summary>
    public NavigationMethod NavigationMethod { get; }

    /// <summary>
    /// Gets or sets any key modifiers active at the time of focus.
    /// </summary>
    public KeyModifiers KeyModifiers { get; }

    /// <summary>
    /// Gets whether focus change is canceled.
    /// </summary>
    public bool Cancelled { get; }

    /// <summary>
    /// Attempts to cancel the current focus change
    /// </summary>
    /// <returns>true if focus change was cancelled; otherwise, false</returns>
    public bool TryCancel();

    /// <summary>
    /// Attempts to redirect focus from the targeted element to the specified element.
    /// </summary>
    public bool TrySetNewFocusedElement(IInputElement? inputElement);
}

Adds the following events and callbacks to InputElement

public static readonly RoutedEvent GettingFocusEvent; public static readonly RoutedEvent LosingFocusEvent; protected virtual void OnGettingFocus(FocusChangingEventArgs e); protected virtual void OnLosingFocus(FocusChangingEventArgs e);

These api allow controls to cancel any focus change that affects them, as long as the toplevel allows. There are situations where cancelling is not allowed, like when the toplevel loses focus.

What is the current behavior?

Focus change can't be cancelled currently. There's no api to lock focus on a control. There are cases where you want to keep keyboard focus on a control while still being able to interact with other controls, like the case of a textbox in a chat app.

What is the updated/expected behavior with this PR?

How was the solution implemented (if it's not obvious)?

Checklist

Breaking changes

Obsoletions / Deprecations

Fixed issues