Reputation: 317
DataGrid
is located on Tab1
. If I am located on Tab2
and I click on the Tab1
header the program switches to Tab1
and the DataGrid
scrolls into view at the right position, but the selected Row
won't get focused(highlighted) unless I click on the Tab1
header again. The rest of the code is triggering just fine.
CS
private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
if (dg_address.SelectedIndex > -1)
{
dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
XAML
<TabControl x:Name="tab_control"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="#FFE5E5E5">
<TabItem>
<TabItem.Header>
<Label Content="Seznam"
MouseLeftButtonDown="Tab1_Clicked"/>
</TabItem.Header>
Upvotes: 1
Views: 100
Reputation: 317
Found a solution here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/3baa240a-c687-449e-af77-989ff4d78333/how-to-move-focus-to-a-textbox-in-a-tabcontrol-on-a-button-click?forum=wpf
private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
if (dg_address.SelectedIndex > -1)
{
dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
Dispatcher.InvokeAsync(() =>
{
DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
);
}
}
or
private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
if (dg_address.SelectedIndex > -1)
{
dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
));
}
}
Edit: Optimized and removed a bug in the code.
Upvotes: 1