مشاركة عبر


Control.Focus(FocusState) Method

Definition

Attempts to set the focus on the control.

public:
 virtual bool Focus(FocusState value) = Focus;
bool Focus(FocusState const& value);
public bool Focus(FocusState value);
function focus(value)
Public Function Focus (value As FocusState) As Boolean

Parameters

value
FocusState

Specifies how focus was set, as a value of the enumeration.

Returns

Boolean

bool

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

Examples

In this example, clicking an "Edit" button causes focus to be set on a TextBox, so the Programmatic focus state is passed to the Focus method.

<StackPanel>
    <Button Content="Edit" Click="Button_Click"/>
    <TextBox x:Name="EditorTextBox" IsReadOnly="True"/>
</StackPanel>
private void Button_Click(object sender, RoutedEventArgs e)
{
    EditorTextBox.IsReadOnly = false;
    EditorTextBox.Focus(FocusState.Programmatic);
}

Remarks

If you call this method on a Control with an IsTabStop set to false, the call will be ignored and focus will not move, and the call will return false.

You can't remove focus from a control by calling this method with Unfocused as the parameter. This value is not allowed and causes an exception. To remove focus from a control, set focus to a different control.

You typically pass FocusState.Programmatic as the parameter to indicate the control obtained focus through a deliberate call to the Focus method. For example, if clicking an "Edit" button causes focus to be set on a TextBox, use the Programmatic focus state.

Pass FocusState.Pointer if you’re setting focus as the direct result of a pointer interaction. Pass FocusState.Keyboard as the parameter if you’re setting focus as a result of a keyboard interaction, like a tab sequence or key press. For example, if you’re implementing an ItemsControl and handle key presses to let the user move focus between items in the control, use the Keyboard focus state when you call Focus in your key press handler.

Notes for previous versions

Note

In Windows 8, when FocusState is Programmatic, the keyboard focus visual is shown even if the prior method of input was pointer. In Windows 8.1, when you call Focus (FocusState.Programmatic), the prior FocusState, either Pointer or Keyboard, is retained so that the correct focus visual is shown. This means that if you check the value of the FocusState property after you call Focus (FocusState.Programmatic), the FocusState property will have a value of either Pointer or Keyboard.

In an app that’s compiled for Windows 8, but run in Windows 8.1, the Windows 8 behavior is retained. The FocusState property value is Programmatic and the keyboard focus visual is shown.

Applies to

See also