How to get focused VisualElement in xamarin?

Viewed 2102
1 Answers

Although VisualElement has Focused and UnFocused event , not all controls will response because the events are belong to the superclass . And it also due to different platforms .

For example , the Focused and UnFocused event of WebView will work on iOS but not on Android .

In your case , Label and Button will not invoke the events in most cases. Entry will been focused when in edit mode (input) and been unfocused when end editing .

So , if you do want to get current focused element , you could define a property in ContentPage .

public object FocusedElement;
private void FocusEvent(object sender, FocusEventArgs e)
{
   FocusedElement = sender; //sender here is the element , like label or entry
}

private void UnfocusEvent(object sender, FocusEventArgs e)
{
   FocusedElement = null;
}

in xaml

Define the Focused and UnFocused event of each Element

 <Label Text="Welcome to Xamarin.Forms!" 
           HorizontalOptions="Center"
               Focused="FocusEvent" Unfocused="Label_Unfocused"
           VerticalOptions="CenterAndExpand" />


        <Button  Focused="FocusEvent" Unfocused="UnfocusEvent" Text="111"/>

        <Entry   Focused="FocusEvent" Unfocused="UnfocusEvent" HeightRequest="50"  WidthRequest="100" /> 
Related