Published articles on other web sites*

Published articles on other web sites*

Display Parent Child collection in WPF DataGrid using Combobox

The DataBinding feature in WPF is excellent, especially in DataGrid scenarios where we receive a parent-child collection from a DAL or an external service and need to display this data in a control like the DataGrid. A common implementation of this scenario is that the DataGrid displays parent data in an individual column and one column of this DataGrid is supposed to display data from a Child collection, using a control like the Combobox.
E.g. Lets consider a scenario where we receive the DepartmentCollection object which contain List of Employees object for that Department, in every row of the Department collection. Now we need to display this data in DataGrid. Let’s how to handle this scenario in WPF:
Consider the Master-Detail Data arrangement as shown below:

WPF DataGrid Comboxbox
To display the data from the ‘DepartmentCollection’ class, the DataGrid is defined with Template Column which further contains the Combobox. The ComboBox is bound with the ‘Employee’ List declared in the Department class. The ItemTemplate of the ComboBox is set to all the properties in the ‘Employee’ class. The XAML is as shown below:
<Window x:Class='WPF40_DataGrid_List_Column.EmpDeptMasterDetails'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:src='clr-namespace:WPF40_DataGrid_List_Column'
Title='EmpDeptMasterDetails by DevCurry.com' Height='320' Width="673">
<Window.Resources>
<src:DepartmentCollection x:Key="DeptCollection">         
</src:DepartmentCollection>
<DataTemplate x:Key='EmpTemplate' DataType='{x:Type src:Employee}">
<StackPanel Orientation="Horizontal">
<TextBlock Text='{Binding EmpNo}"></TextBlock>
<TextBlock Text='{Binding EmpName}"></TextBlock>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid DataContext='{Binding Source={StaticResource DeptCollection}}">
<DataGrid AutoGenerateColumns='False'
Height='219' HorizontalAlignment='Left'
Margin='37,24,0,0' Name='dataGrid1' VerticalAlignment='Top'
Width='520' ItemsSource='{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header='DeptNo' Binding='{Binding DeptNo}" />
<DataGridTextColumn Header='DeptName' Binding='{Binding DeptName}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Width='100' SelectedIndex='0'
ItemsSource='{Binding Path=Employee}'
ItemTemplate='{StaticResource EmpTemplate}">                             
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
After running the application, here’s the output:
WPF DataGrid Comboxbox
"

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...