Search code examples
textboxwinui-3

Setting `IsTabStop` on `TextBox` makes it unclickable


I would like to prevent entering TextBox via TAB key, so I set IsTabStop to false, but it completely prevents the control to have focus by simple mouse click on it?

How can we prevent Tab Stopping, but allowing control to work normally if clicked?

I tried changing the IsTabStop of TextBox, but it prevents it to have focus.


Solution

  • From the doc:

    if IsTabStop is false, the control cannot receive input focus. (If you try to set focus programmatically, by calling the Focus method, Focus returns false).

    UPDATE

    You can wrap the TextBox with a Grid and use it to switch IsTabStop:

    <Grid
        x:Name="TextBoxGrid"
        Background="Transparent"
        Tapped="TextBoxGrid_Tapped">
        <TextBox
            x:Name="TextBoxControl"
            IsHitTestVisible="False"
            IsTabStop="False"
            PlaceholderText="TextBox #2" />
    </Grid>
    
    private void TextBoxGrid_Tapped(object sender, TappedRoutedEventArgs e)
    {
        TextBoxControl.IsTabStop = true;
        TextBoxControl.IsHitTestVisible = true;
        TextBoxControl.Focus(FocusState.Programmatic);
        TextBoxControl.LostFocus -= TextBoxControl_LostFocus;
        TextBoxControl.LostFocus += TextBoxControl_LostFocus;
    }
    
    private void TextBoxControl_LostFocus(object sender, RoutedEventArgs e)
    {
        TextBoxControl.IsTabStop = false;
        TextBoxControl.IsHitTestVisible = false;
    }