Search code examples
c#xamarin.formsfocus

How to get focused VisualElement in xamarin?


i have to show more than 10 ContentPages in a CarouselPage in xamarin, and in each ContentPage there are many Labels, Buttons ,Entries. so how can i current focused VisualElement.

I found events VisualElement.Focused,VisualElement.Unfocused,VisualElement.FocusChangeRequested.

But none can help me.


Solution

  • 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" />