I have a WPF Datagrid with 3 columns as part of a window. The ItemsSource is set from an array of payment objects (grdPayments.ItemsSource = payments). When the focus is set to the grid in code behind I want the third cell in the first row to get focus.
Regardless of which of the following methods that I use, the 2nd row is selected and focused rather than the 1st.
This sets focus to the 3rd cell in the 2nd row:
grdPayments.Focus();
grdPayments.CurrentCell = new DataGridCellInfo(grdPayments.Items[0],grdPayments.Columns[2]);
grdPayments.SelectedCells.Add(dataGridCellInfo);
cell.Focus();
grdPayments.BeginEdit();
This sets focus to the 2nd row:
grdPayments.Focus();
grdPayments.SelectedIndex = 0;
grdPayments.BeginEdit();
Can anyone tell me whats going on? The DataGrid XAML is below. my:NumberEntry is a custom control:
<DataGrid Name="grdPayments"
AutoGenerateColumns="False"
Background="#FF21B721"
ItemsSource="{Binding}"
SelectionUnit="Cell"
SelectionMode="Single"
Margin="5"
VirtualizingPanel.IsVirtualizing="False">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#FF21B721"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Width="240"
Binding="{Binding Path=Description}"
Header="Description"
IsReadOnly="True"
TextBlock.TextAlignment="Center">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{StaticResource clBr}"/>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTemplateColumn Width="100" Header="Due">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="100" Text="{Binding Path=Due, Converter={StaticResource CurrencyPadder}, ConverterParameter=10}" Background="{StaticResource clBr}" Focusable="False"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="100" Header="Paid">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="{StaticResource clBr}"/>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<my:NumberEntry Decimals="2"
LostFocus="NumberEditor_LostFocus"
PreviewKeyDown="NumberEditor_PreviewKeyDown"
MaxLength="10"
TextAlignment="Right"
Text="{Binding Path=Paid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>