Unknown Coder
Unknown Coder

Reputation: 6731

WPF - example with DataGridComboBoxColumn

I have a datagrid with 2 columns. One column contains role information, the other column should have a combo box with a list of available users. The data in the combobox is unrelated to the data in the first column.

I'm thrown off by the fact that the combobox does not have a datacontext, only an itemsource and I can't seem to use binding either.

What is the method that uses two different data sets for the data in a table and in the combo box?

Upvotes: 15

Views: 38595

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31606

Instead of using DataGridTextColumn one uses a DataGridComboBoxColumn instead. Then one fills in the data using the ItemsSource, which in the below example points to an external enum in the static resource, and finally one binds the result to the target object which will hold the user selection in the SelectedItemBinding.

<DataGrid.Columns>

<DataGridComboBoxColumn Header="MySelections"  
                        SelectedItemBinding="{Binding MySelectionsProperty}" 
                        ItemsSource="{Binding Source={StaticResource mySelectionsEnum}}" />
</DataGrid.Columns>

See a full example on MSDN at DataGridComboBoxColumn Class

Upvotes: 4

Aran Mulholland
Aran Mulholland

Reputation: 23935

the columns in the datagrid dont have a datacontext, as they are never added to the visual tree. sound a bit wierd but have a look at vinces blog, its got a good example of the visual layout. once the grid is drawn the cells have a data context and you can set the combo boxes items source in them using normal bindings (not static resources..)

you can access the combo box items source as such

   <dg:DataGridComboBoxColumn>
      <dg:DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=MyBindingPath}" />
        </Style>
      </dg:DataGridComboBoxColumn.EditingElementStyle>
   </dg:DataGridComboBoxColumn>

have a look here and also here for some code

Upvotes: 9

Related Questions