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);
}
This should be work like this (over your defined Initialized event of the UserControl):
private void ViewInitialized(object sender, System.EventArgs e)
{
this.SearchButton.Focus();
}
您需要在视图上预订Loaded事件,并在事件处理程序方法中调用按钮上的Focus()。
It seemed to bit a bit strange...
IsVisibleChanged ... no reaction
Initialized ... no reaction
Loaded ... no reaction
And then I got the solution. What if the runtime uses the same View for each tab and changes only the data inside to another ViewModel. So the solution is:
private void SameViewButDataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
ChangeFocusDelegate focusDelegate = FocusFileSearchButton;
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, focusDelegate);
}
And each time I add a tab the focus is switched to the Search button.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.