Question

I have a ComboBox in a DataGridTemplateColumn :

     <DataGrid x:Name="dataVoitures" Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding ListBagnoles}" 
              CanUserAddRows="False">
        <DataGrid.Columns>
         ...
            <DataGridTemplateColumn Header="Carburant" SortMemberPath="Carburant.NomCarburant">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Carburant.NomCarburant}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <ComboBox x:Name="comboCarbu" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, 
                            Path=DataContext.ListeCarburants}" 
                                  SelectedItem="{Binding Carburant, UpdateSourceTrigger=PropertyChanged}" 
                                  DisplayMemberPath="NomCarburant" IsDropDownOpen="True" Initialized="comboCarbu_Initialized"/> 
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
            ...
        </DataGrid.Columns>

The problem is when I add a new row in the Datagrid, I cannot select an item from the combobox with the keyboard.

With debugging, I found that when I come to the ComboBox cell with Key Tab, the ComboBox.GotFocus is not triggered.

I try forcing the ComboBox to get the focus when Combobox is initialized but cannot acces to the combobox in code-behind oO.

Hope you can help me :)

Was it helpful?

Solution

I found my way using this post : Find a WPF element inside DataTemplate in the code-behind

I just add the FindVisualChildren method to my class and force the focus to the combobox when the ComboBox_Initialized handler is triggered :

    private void comboCarbu_Initialized(object sender, EventArgs e)
    {
        foreach (var combobox in FindVisualChildren<ComboBox>(dataVoitures))
        {
            if (combobox.Name == "comboCarbu")
            {
                combobox.Focus();
            }
        }
    }

Now I can select an item from my Combobox with tab key :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top