Search code examples
uwpuwp-xamlwindows-community-toolkit

How to avoid loss Focusing of TextBox in UWP?


What I have tried?

<Grid >
    <Canvas>
        <Canvas x:Name="Gesture" Width="500" Height="500" Background="Gray" AllowFocusOnInteraction="False">
            
        </Canvas>
        <StackPanel x:Name="SidePanel" Canvas.Left="500" Background="LightCyan" Width="100" Height="500">
            <TextBox x:Name="NameBox" Text="Prem" Width="100" Height="35"/>
            <Button Content="But" AllowFocusOnInteraction="False"/>
        </StackPanel>
    </Canvas>
</Grid>

What I need to achieve?

While the Textbox got focus, if I click on Button it won't loss focus. Because, I set the Button property - AllowFocusOnInteraction="False".

I need to achieve the same, when I click inside the Gray area(Gesture Canvas).I have set the Canvas Property-AllowFocusOnInteraction="False". But it won't work.

The textbox should be focused when I Click inside the Gesture canvas. How to Do it? Why AllowFocusOnInteraction won't work on Gesture Canvas?


Solution

  • You could set the focus states in the LostFocus event to make sure your TextBox won't lose focus.

    You could handle the LostFocus event of the TextBox and the Tapped event of the StackPanel. Then when the StackPanel is clicked, change the flag value and set the focus state in the LostFocus event

     <StackPanel x:Name="SidePanel" Canvas.Left="500" Background="LightCyan" Width="100" Height="500" Tapped="SidePanel_Tapped">
                <TextBox x:Name="NameBox" Text="Prem" Width="100" Height="35" LostFocus="NameBox_LostFocus"/>
                <Button Content="But" AllowFocusOnInteraction="False"/>
            </StackPanel>
    

    Code behind

    private bool setFocus = true;
    
     private void NameBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (setFocus == true)
            {
                NameBox.Focus(FocusState.Programmatic);
            }
        }
    
        private void SidePanel_Tapped(object sender, TappedRoutedEventArgs e)
        {
            setFocus = true;
        }