proman
proman

Reputation: 277

Windows Phone 8.1 XAML App. How to prevent inappropriate automatic focus change?

Imagine the following simple page markup:

<Page
    x:Class="AutoFocusBug.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel>
        <!--<Button x:Name="FocusHolder" Width="0" Height="0" MinHeight="0" MinWidth="0"/>-->
        <TextBox Text="zxczczczczx"/>
        <Button x:Name="Button1" Content="Button1" Click="ButtonBase_OnClick"/>
    </StackPanel>
</Page>

and the following code-behind:

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    Button1.Visibility = Visibility.Collapsed;
}

When I click Button1 button it hides (which is expected and desired) but for some reason TextBox automatically gets focus and on-screen keyboard appears. I don't want this unexpected auto-focus.

I can try to do something with focus in Click handler but in real app it is implemented with ViewModel with commands and so on and it looks like dirty hack (and also keyboard appears for short period even if I change focus immediately after hiding button).

The second approach I found is to create "invisible" button somewhere before the textbox (commented FocusHolder) which is quite better but also doesn't look like correct technique.

So, what is that? Is this some mechanism that I can somehow configure to "redirect" focus from collapsed element? Or is it a bug? What is the right way to prevent this undesired auto-focus?

Upvotes: 6

Views: 1620

Answers (3)

Mato Peto
Mato Peto

Reputation: 96

Try to set TabNavigation="Cycle" to the Button. This is working for me.

Upvotes: 0

JP3PO
JP3PO

Reputation: 41

I was able to solve this issue by setting the TabIndex.

Set the index order to focus on your second control before the TextBox.

<Page
x:Class="AutoFocusBug.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<StackPanel>
    <!--<Button x:Name="FocusHolder" Width="0" Height="0" MinHeight="0" MinWidth="0"/>-->
    <TextBox Text="zxczczczczx" TabIndex="2"/>
    <Button x:Name="Button1" Content="Button1" Click="ButtonBase_OnClick" TabIndex="1"/>
</StackPanel>

Upvotes: 4

Barnstokkr
Barnstokkr

Reputation: 3129

The reason for this is due to to the Tab index switching from the button to the Textbox. This is a very annoying thing of WP8.1. I have not found a "good" solution for this, but this might be cleaner than your current solution.

The xaml

<TextBox x:Name="myTextBox" Text="zxczczczczx"/>

The function

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    myTextBox.IsTabStop = false;
    Button1.Visibility = Visibility.Collapsed;
    myTextBox.IsTabStop = true;
}

Good luck.

Upvotes: 4

Related Questions