Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
proman Avatar asked Jan 05 '15 11:01

proman


2 Answers

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.

like image 93
Barnstokkr Avatar answered Sep 30 '22 14:09

Barnstokkr


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>

like image 42
JP3PO Avatar answered Sep 30 '22 14:09

JP3PO