FocusManager.TryFocusAsync(DependencyObject, FocusState) FocusManager.TryFocusAsync(DependencyObject, FocusState) FocusManager.TryFocusAsync(DependencyObject, FocusState) FocusManager.TryFocusAsync(DependencyObject, FocusState) Method

Definition

Asynchronously attempts to set focus on an element when the application is initialized.

public : static IAsyncOperation<FocusMovementResult> TryFocusAsync(DependencyObject element, FocusState value)
static IAsyncOperation<FocusMovementResult> TryFocusAsync(DependencyObject element, FocusState value) const;
public static IAsyncOperation<FocusMovementResult> TryFocusAsync(DependencyObject element, FocusState value)
Public Shared Function TryFocusAsync(element As DependencyObject, value As FocusState) As IAsyncOperation(Of FocusMovementResult)

Parameters

element
DependencyObject DependencyObject

The object on which to set focus.

value
FocusState FocusState

One of the values from the FocusState enumeration that specify how an elemnent can obtain focus.

Returns

Additional features and requirements

Device family
Windows 10, version 1803 (introduced v10.0.17134.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v6)

Examples

Here, we show how to set focus on a WebView object, and, if that fails, restore focus to the original element.

async void MoveFocus(WebView webView)) 
{ 
    FocusMovementResult result; 
    result = await FocusManager.TryFocusAsync(webView, FocusState.Programmatic); 
    if (!result.Succeeded) 
    { 
        // Restore focus to original element. 
        this.Focus(FocusState.Programmatic); 
    } 
}

Remarks

Some objects, such as a WebView, can run in either the app process or in a separate process (see WebViewExecutionMode.SeparateProcess ).

When an object runs in the app process, the following focus events occur as expected for both the previously focused object and the newly focused object:

However, if the newly focused object is running in a separate process some of these event behaviors can differ.

  • GetFocusedElement does not return the newly focused object until the TryFocusAsync operation completes.
  • The control losing focus receives its LosingFocus event synchronously, but does not receive LostFocus until the asynchronous operation completes.
  • The control getting focus receieves its GettingFocus event synchronously, but does not receive GotFocus until the asynchronous operation completes.

TryFocusAsync completes synchronously when called on an element running in the app process.