I have WPF DataGrid
placed on the Window
. I have a button which performs some business logic and populates the grid.
I want to set focus on the DataGrid
(preferably first row in the DataGrid) when i TAB
from the button. I have set the TabIndex
but somehow the focus does not come on the DataGrid.
The relevant part of the form's XAML is here:
<StackPanel Orientation="Vertical" Grid.Column="2" Margin="20,10,10,10">
<Button Content="Search"
Height="25" HorizontalAlignment="Right" Margin="0,-25,0,0"
Name="btnSearch" VerticalAlignment="Top" Width="75" **TabIndex="1300"** Click="btnSearch_Click" Keyboard.KeyDown="btnSearch_PreviewKeyDown" LostFocus="btnSearch_LostFocus"/>
</StackPanel>
<DataGrid AutoGenerateColumns="False" Grid.Column="1" Margin="20,160,10,10" Name="dataGridOrganisations" **TabIndex="1400"**
BorderThickness="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Focusable="True"
ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" GridLinesVisibility="None"
ItemsSource="{Binding}" CanUserReorderColumns="False" CanUserResizeRows="False" IsReadOnly="True" SelectionChanged="dataGridOrganisations_SelectionChanged" Keyboard.PreviewKeyDown="dataGridOrganisations_PreviewKeyDown" >
<DataGrid.Columns>
<DataGridTextColumn Header="Shortname" Width="100" Binding="{Binding ShortName}" />
<DataGridTextColumn Header="Internal Code" Width="100" Binding="{Binding LocalID}"/>
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
When I added following code on Button's LostFocus
event, it highlights the first row. But when I use 'down' arrow key to select next row in the grid; instead of going to next row it first sets focus on the 'Search' button and next time goes to second row!
if (this.dataGridOrganisations != null && this.dataGridOrganisations.HasItems)
{
this.dataGridOrganisations.Focus();
if (dataGridOrganisations.Items != null && dataGridOrganisations.Items.Count > 0)
{
DataGridRow firstRow = this.dataGridOrganisations.ItemContainerGenerator.ContainerFromItem(dataGridOrganisations.Items[0]) as DataGridRow;
if (firstRow != null)
{
firstRow.IsSelected = true;
}
}
}
How to set focus on the DataGrid (or its first row)? Why TabIndex
does not work here?