Steve Mitcham
Steve Mitcham

Reputation: 5313

Setting Focus on new Items in Items Control

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.

Upvotes: 5

Views: 2379

Answers (1)

Jeff Wain
Jeff Wain

Reputation: 1022

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>

Upvotes: 7

Related Questions