WPF DataGrid using a DataGridTemplateColumn rather than a DataGridComboBoxColumn to show selected value at load

Posted by T on Geeks with Blogs See other posts from Geeks with Blogs or by T
Published on Wed, 28 Nov 2012 13:43:53 GMT Indexed on 2012/11/28 17:06 UTC
Read the original article Hit count: 245

Filed under:

My problem was that using a DataGridComboBoxColumn I couldn’t get it to show the selected value when the DataGrid loaded.  Instead, the user would have to click in the cells and like magic, the current selected values would appear and it looked the way I wanted it to on load.

Here is what I had

<DataGridComboBoxColumn MinWidth="150" x:Name="crewColumn" Header="Crew" 
     ItemsSource="{Binding JobEdit.Crews, Source={StaticResource Locator}}"  
     DisplayMemberPath="Name" 
     SelectedItemBinding="{Binding JobEdit.SelectedCrew, Mode=TwoWay, Source={StaticResource Locator}}" 
 />

 

Here is what I changed it too.  This works great.  It displays the selected item when the DataGrid loads and shows the combo box when the user goes into edit mode.

 

                           <DataGridTemplateColumn Header="Crew" MinWidth="150">
                                       <DataGridTemplateColumn.CellTemplate>
                                           <DataTemplate>
                                                <TextBlock Text="{Binding Crew.Name}"></TextBlock>
                                            </DataTemplate>
                                        </DataGridTemplateColumn.CellTemplate>
                                        <DataGridTemplateColumn.CellEditingTemplate>
                                            <DataTemplate>
                                                <ComboBox ItemsSource="{Binding JobEdit.Crews, Source={StaticResource Locator}}"  
                                                   DisplayMemberPath="Name" SelectedItem="{Binding JobEdit.SelectedCrew, Mode=TwoWay, 
                                                   Source={StaticResource Locator}}"></ComboBox>
                                            </DataTemplate>
                                        </DataGridTemplateColumn.CellEditingTemplate>
                                    </DataGridTemplateColumn>

© Geeks with Blogs or respective owner