views:

247

answers:

1

I've got a ListBox which is getting new items added to it through Databinding (i.e. something is getting added to the list and the box is updating to include the new item).

The items in the list box are editable data templates, so the question is: How do I set the focus to the first field in the template when a new item is added?

I've looked at this question and am going to see if it gets me anywhere, but it is not really a direct response to my question.

+3  A: 

The question you linked to should work for your particular situation. As long as you are using an ObservableCollection for your source, you can set:

<ListBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding MyCollection}" ItemTemplate="{StaticResource MyTemplate}/>

This will make sure that as items are added, focus is given to the new item then the focus manager (take a look at the first response in that thread) should give focus to the TextBox. The MSDN article supplies a helpful example, put into a template here:

<DataTemplate x:Key="MyTemplate" DataType="{x:Type Classes:MyClass}">    
  <StackPanel FocusManager.FocusedElement="{Binding ElementName=firstButton}">
    <Button Name="firstButton" />
  </StackPanel>
</DataTemplate>
Jeff Wain
My issue actually gets more complicated due to the presence of a UserControl in the data template that requires handling the focus event and passing it to the actual text box that I want, but the settings here got me far enough to figure it out, thanks.
Steve Mitcham
You might post your code in case anyone else comes looking for something similar.
Jeff Wain