I’m trying to rig up a ComboBox with a Datagrid dropdown in WPF. I need the the code to be done programmatically and contained in the codebehind.
Here’s what I’ve got so far:
Dim cb As New ComboBox
Dim dg As New DataGrid
dg.AutoGenerateColumns = False
dg.ItemsSource = clnObjects
Dim col_name As New DataGridTextColumn
col_name.Header = "Name"
col_name.Binding = New Binding("Name")
col_name.CanUserSort = False
col_name.CanUserResize = False
dg.Columns.Add(col_name)
Dim col_startdate As New DataGridTextColumn
col_startdate.Header = "Start Date"
col_startdate.Binding = New Binding("StartDate")
col_startdate.CanUserSort = False
col_startdate.CanUserResize = False
dg.Columns.Add(col_startdate)
cb.Items.Add(dg)
This code produces a ComboBox that contains a DataGrid with two columns and seems to look fine. Although when you click on the ComboBox and select one of the rows in the DataGrid the selection in the ComboBox doesn’t work properly. (It just shows the colum headers.)
I want the value in the first column of the selected row to appear as the ComboBox selection.
If anyone can help me with this issue it would be greatly appretiated.
Thanks,
Mike
It sounds like your want your
ComboBoxto contain items fromclnObjects, but to display the DropDown using aDataGrid, not the defaultStackPanel.Right now your
ComboBoxis full ofDataGridcontrols, not whatever object is inclnObjects. This means when you select an item, you’re selecting aDataGrid, not theDataGrid.SelectedItemYou could try changing it so the ComboBox’s display text contains
ComboBox.SelectedItem.SelectedItemwhere the firstSelectedItemis the DataGrid, however I still feel this is a bad design since you need to create a newDataGridobject perComboBoxItemInstead I would recommend overwritting the default
ComboBox.Templateto display the ComboBox items in aDataGridinstead of in the default StackPanel. The default ComboBox Template can be found here. Just copy it and replace the StackPanel withIsItemsHost="True"to a DataGrid