<p>I have <code>DataTemplate</code> containing a <code>TextBox</code>. I'm setting this template to a listbox item on a selection.</p>

<p>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.</p>

<p>How can I access it?</p>

Since you know the name of the
```
TextBox
```
you want to focus, this becomes relatively easy. The idea is to get hold of the template as it's applied to the
```
ListBoxItem
```
itself.
First thing you want to do is get the selected item:
```
```
var item = listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem) as ListBoxItem;
```
```
Then you can pass that into this little helper function which focuses a control based on its name:
```
```
public void FocusItem(ListBoxItem item, string name)
{
    if (!item.IsLoaded)
    {
        // wait for the item to load so we can find the control to focus
        RoutedEventHandler onload = null;
        onload = delegate
        {
            item.Loaded -= onload;
            FocusItem(item, name);
        };
        item.Loaded += onload;
        return;
    }

    try
    {
        var myTemplate = FindResource("MyTemplateKey") as FrameworkTemplate; // or however you get your template right now

        var ctl = myTemplate.FindName(name, item) as FrameworkElement;
        ctl.Focus();
    }
    catch
    {
        // focus something else if the template/item wasn't found?
    }
}
```
```
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.StatusChanged
```
event and sometimes the
```
ListBoxItem
```
hadn't been fully initialized by the time we entered the method.