I have DataTemplate containing a TextBox. I’m setting this template to a listbox item on a selection.
I’m unable to set focus to textbox in the template. I tried to call MyTemplate.FindName, but it ends up with an Invalid Operation Exception: This operation is valid only on elements that have this template applied.
How can I access it?
Since you know the name of the
TextBoxyou want to focus, this becomes relatively easy. The idea is to get hold of the template as it’s applied to theListBoxItemitself.First thing you want to do is get the selected item:
Then you can pass that into this little helper function which focuses a control based on its name:
I guess the tricky bit is making sure you wait for the item to load. I had to add that code because I was calling this from the
ItemContainerGenerator.StatusChangedevent and sometimes theListBoxItemhadn’t been fully initialized by the time we entered the method.