Focus on a TextBox in a DataTemplate

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 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;

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

        var ctl = myTemplate.FindName(name, item) as FrameworkElement;
        // 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.

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.


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


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

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

Need Your Help

How to populate UITableView from the bottom upwards?

ios objective-c iphone uitableview ios8

is it possible to reverse the order of a tableView. I have searched a lot for a solution but all the results have not quite been a solution to what I am trying to achieve. They all suggest scrollin...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.