I use a TabControl to display a list of items. The ItemView is a separate control I wrote.
<TabControl SelectedItem="{Binding CurrentItem}"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding ItemList}">
<TabControl.ContentTemplate>
<DataTemplate>
<ctrls:ItemView/>
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShortItemDescription}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
If the user presses a Button a new ViewModel is added to the list of ViewModels and the TabControl displays it as a new tab. After adding the new tab is selected.
<Button Command="{Binding AddItemCommand}"
Content="Add item"/>
Inside of the new View is a button that needs to be focused each time a new tab is added. I have tried to use the FocusManager and the Initialized event in the ItemView but these are only called for the first time I add a new tab.
<UserControl x:Class="ItemView"
...
Initialized="ViewInitialized">
<Grid>
...
<!-- Set focus to this button -->
<Button Content="Search"
Command="{Binding SearchCommand}"
Name="SearchButton"
Grid.Column="0"
Grid.Row="0"/>
</Grid>
</UserControl>
Any ideas?
Update
The content of the Initialize method in the ItemView is currently this one - which is working fine... for the first time and then never again
public delegate void ChangeFocusDelegate();
private void FocusSearchButton()
{
SearchButton.Focus();
}
private void ViewInitialized(object sender, EventArgs e)
{
ChangeFocusDelegate focusDelegate = FocusSearchButton;
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, focusDelegate);
}