共用方式為


GotFocus

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

Occurs when an object receives focus.

<object GotFocus="eventhandlerFunction"  .../>
[token = ]object.AddEventListener("GotFocus", eventhandlerFunction)

Arguments

AddEventListener Parameters

token

integer

A token that is returned from the function, which you can optionally retain as a variable. If you intend to call RemoveEventListener to remove the handler, you will need this token.

eventhandlerFunction

object

The name of your event handler function as it is defined in script. When used as an AddEventListener parameter, quotation marks around the function name are not required. (See the "Remarks" section.)

Event Handler Parameters

sender

object

The object that invoked the event.

eventArgs

object

eventArgs.Source: Reports the object that raised the event. (Silverlight 2)

Managed Equivalent

GotFocus

Remarks

Use the GotFocus event to specify actions when the Silverlight content or specific controls within it gain focus. For purposes of controls (TextBox or PasswordBox), GotFocus is a bubbling event, so you can handle GotFocus on the control that received focus, or on any parent object (the parent object itself does not have to be focusable to receive the routed event).

You can also add handlers in script by using a quoted string for the event handler name, as follows:

object.AddEventListener("GotFocus", "eventhandlerFunction")

This syntax also returns a token. However, the token is not an absolute requirement for removing the handler in cases where the handler was added by using a quoted string. For details, see RemoveEventListener.

In some browsers, the GotFocus event is raised while the Silverlight plug-in is initally loading into the HTML page, depending on how that browser treats focus setting upon initiation in its control or plug-in model.

Example

The following XAML example shows GotFocus and LostFocus events defined for the root Canvas object.

<Canvas
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  GotFocus="onGotFocus"
  LostFocus="onLostFocus">

  <TextBlock x:Name="myTextBlock" />

</Canvas>

The following JavaScript example shows how to implement GotFocus and LostFocus event handler functions. In this case, the text in the TextBlock changes when focus is received or lost.

function onGotFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "got focus";
}

function onLostFocus(sender, eventArgs)
{
    sender.findName("myTextBlock").Text = "lost focus";
}

Applies To

Border (Silverlight 2)

Canvas)

Grid (Silverlight 2)

PasswordBox (Silverlight 2)

Popup (Silverlight 2)

StackPanel (Silverlight 2)

TextBox (Silverlight 2)

See Also

Reference