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'
Title='EmpDeptMasterDetails by' Height='320' Width="673">
<src:DepartmentCollection x:Key="DeptCollection">         
<DataTemplate x:Key='EmpTemplate' DataType='{x:Type src:Employee}">
<StackPanel Orientation="Horizontal">
<TextBlock Text='{Binding EmpNo}"></TextBlock>
<TextBlock Text='{Binding EmpName}"></TextBlock>
<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}">
<DataGridTextColumn Header='DeptNo' Binding='{Binding DeptNo}" />
<DataGridTextColumn Header='DeptName' Binding='{Binding DeptName}" />
<ComboBox Width='100' SelectedIndex='0'
ItemsSource='{Binding Path=Employee}'
ItemTemplate='{StaticResource EmpTemplate}">                             
After running the application, here’s the output:
WPF DataGrid Comboxbox

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...