The last time I focus alot on question regarding Windows 8 metro style development on Stackoverflow because I really like the new WinRT development environment and already have been doing some metro style app developement. A few days ago I saw this question on Stackoverflow and was interested, because it seems pretty simple. The question was that the asker was not able to set the focus to an input textfield.
First I tried it myself just with a little project, click a button and set the focus on the textbox. So far no problems, works like a charm. I send my testproject to the asker and asked him to test this on his machine to check if this works. Now the asker came up with additional requirements. (Just like every project
) The focus needs to be set to the textbox when he has clicked a item in a listview. I have updated my project, added a listview with some testdata, attach the “iteminvoked” eventhandler to the listview and within the handler set the focus to the textbox. That’s where the problems start, somehow the focus is not set to the textbox anymore.
I started playing around with adding eventhandlers to the textbox and the listview “focusin” and “focusout” events. I saw that the textbox got focus but lost it when the “blur” event is re-attached to the listview. On MSDN I found the msSetImmediate method which I added to the “iteminvoked” event handler so the focus is set immediate after the processing is completed.
My code for attaching the “iteminvoked” eventhandler looks now like below.
var listView = document.getElementById("basicListView"); listView.winControl.addEventListener("iteminvoked", function (evt) { if (listView.winControl.selection.count() > 0) { msSetImmediate(setFocus); } });
And below the code for the setFocus function.
function setFocus() { //Set focus on input textbox; var input = document.querySelector("#input-box") input.focus(); }
Now when we run the solution and click an item in the listview, the focus is set to the textbox. For me it’s not totally clear why this is needed to make this work, but for now (Windows 8 Consumer Preview) this works.
The entire solution can be downloaded here TestFocusApplication
Happy developing!