locked
Control.Focus(Windows.UI.Xaml.FocusState.Programmatic) not working (Win8.1 App) RRS feed

  • Question

  • My problem is when there is focus on a button and i click the spacebar, the buttonEvent gets triggered. This is a normal of course, although the problem is that I set focus to another control, and the button event STILL gets fired when i press the spacebar.

    Here is the scenerio.

    • I have several buttons and a textblock. 
    • All the buttons have a dynamically created event 
    b.Click += new RoutedEventHandler(OnButtonClick);
    • No Matter where I add the following code, It does not set focus on the TEXTBLOCK (do no confuse with textBOX). 

    tb.Focus(Windows.UI.Xaml.FocusState.Programmatic);

    or

    this.Focus(Windows.UI.Xaml.FocusState.Programmatic); // doesn't work either

    So whenever I run an action (in this case Im reading each keystroke the user types in), I always set the focus on this.focus or tb.focus but as soon as i press SPACEBAR the (OnButtonClick) gets called.

    Each key I press sets the focus back to the textblock & Each button i click sets the focus back to the textblock and still whenever i press the SPACEBAR the OnButtonClick gets called.

    Also If a Click Button#3, the button event sets focus to the textblock. As soon as i type Spacebar it fires OnButtonClick of Button#3 the last button I clicked on screen. 

    Why? what am i doing wrong, what am i missing? 

    Wednesday, October 23, 2013 5:00 PM

Answers

  • You need to set the focus to a valid object. If you check the return value from the Focus() call you will see it is false.

    The TextBlock isn't focusable and can't be a tabstop.

    Setting the Focus to the page should work if you set the page's IsTabStop property to true. Consider if this behavior will confuse the user before doing it though.

    --Rob

    • Marked as answer by Joe Cavaliere Wednesday, October 23, 2013 8:20 PM
    Wednesday, October 23, 2013 7:34 PM
    Moderator

All replies

  • You need to set the focus to a valid object. If you check the return value from the Focus() call you will see it is false.

    The TextBlock isn't focusable and can't be a tabstop.

    Setting the Focus to the page should work if you set the page's IsTabStop property to true. Consider if this behavior will confuse the user before doing it though.

    --Rob

    • Marked as answer by Joe Cavaliere Wednesday, October 23, 2013 8:20 PM
    Wednesday, October 23, 2013 7:34 PM
    Moderator
  • ! NICE ! It works

    So for those reading this, I have added the following

    this.IsTabStop = true;

    to make my page "focusable", and then whenevr I needed to lose focus of a control I would call 

    this.Focus(Windows.UI.Xaml.FocusState.Programmatic);

    And this works exactly how I intended for it to work.

    thanks Rob!



    • Edited by Joe Cavaliere Wednesday, October 23, 2013 8:19 PM typo
    Wednesday, October 23, 2013 8:19 PM