Setting Focus from XAML

Andrew 16 Reputation points
2020-12-15T18:03:30.667+00:00

Is there a way to set the focus of an element in XAML? I'm trying to avoid using Code-Behind as much as possible and I know that this can be achieved in WPF using the FocusManager using the following:

FocusManager.FocusedElement="{Binding ElementName=NameOfYourTextBox}"

However, I can't get this to work in Xamarin Forms. Even if I add the presentation namespace I get an error indicating that FocusManager doesn't have a property named FocusedElement.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,364 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,961 Reputation points
    2020-12-16T08:49:34.82+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    To use the FocusManager in xaml, please add an XML namespace declaration for the Xamarin.Forms.Platform.WPF assembly and namespace.

       <wpf:FormsApplicationPage ...  
            xmlns:wpf="clr-namespace:Xamarin.Forms.Platform.WPF;assembly=Xamarin.Forms.Platform.WPF">  
           <wpf:FocusManager .../>  
       </wpf:FormsApplicationPage>  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.