Focus on a TextBox in a DataTemplate

Dusan Kocurek picture Dusan Kocurek · Nov 30, 2008 · Viewed 13.3k times · Source

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?

Answer

Jay picture Jay · Jun 25, 2010

I know this is old, but I ran across this issue today and in the end came up with this resolution:

Since the TextBox is only being loaded when an item is selected, and that is when you want focus to be set, you can simply handle the TextBox.Load event and call Focus().

There are two ways to achieve this.

1. Replace the TextBox in the DataTemplate with an AutoFocusTextBox.

public class AutoFocusTextBox : TextBox
{
    public AutoFocusTextBox()
    {
        Loaded += delegate { Focus(); }; 
    }
}

Don't forget you'll need to reference the namespace in which AutoFocusTextBox is defined in your .xaml file.

2. Add a handler in the codebehind of the file where the DataTemplate is defined.

SomeResourceDictionary.xaml

<TextBox Text="{Binding Something, Mode=TwoWay}" Style={StaticResource ...
        Loaded="FocusTextBoxOnLoad" />

SomeResourceDictionary.xaml.cs

    private void FocusTextBoxOnLoad(object sender, RoutedEventArgs e)
    {
        var textbox = sender as TextBox;
        if(textbox == null) return;
        textbox.Focus();
    }

With either option, you can always add other behaviour in the handler, such as selecting all text.