Partager via


Control.Focus Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Attempts to set the focus on the control.

Namespace:  System.Windows.Controls
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
Public Function Focus As Boolean
public bool Focus()

Return Value

Type: System.Boolean
true if focus was set to the control, or focus was already on the control. false if the control is not focusable.

Remarks

Calling Focus raises the GotFocus or LostFocus events on appropriate elements if focus actually changed (a true return value and focus was not already on that control).

In order to be focusable, the following must be true:

Visibility is set to Visible.

  • IsTabStop is set to true.

  • IsEnabled is set to true.

  • The control must be instantiated in the tree (the Loaded event has fired and the control connects to the root object that is the Silverlight plug-in content).

Although the "FocusedElement" value (exposed via GetFocusedElement method) is updated immediately, the change notifications of GotFocus and LostFocus occur asynchronously. This asychronous focusing design is intended to assure that elements that are created at run-time do not fail in calls to Focus because the acting FocusManager was not updated to the latest view of the visual tree.

Examples

The following example sets focus on the control when the user clicks on it.

Protected Overloads Overrides Sub OnMouseLeftButtonDown(ByVal e As MouseButtonEventArgs)
    MyBase.OnMouseLeftButtonDown(e)
    Focus()
End Sub
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
    base.OnMouseLeftButtonDown(e);
    Focus();
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.