Search code examples
.netwpfxamldatagridbinding

DataGridComboBoxColumn data binding


I am trying to databind DataGridComboBoxColumn

<DataGridComboBoxColumn Header="Number of Copies" SelectedItemBinding="{Binding NumberCopies}">
    <DataGridComboBoxColumn.ElementStyle>
       <Style TargetType="ComboBox">
          <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/>
          <Setter Property="IsReadOnly" Value="True"/>
       </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

What I am doing wrong here , because I am getting an empty combobox in the run time .


I got following

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=LifeAreaList; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=49475561); target property is 'ItemsSource' (type 'IEnumerable')


Solution

  • DataGridColumn doesn't derive from FrameworkElement or FrameworkContentElement so it isn't in the visual tree and doens't have a DataContext and that's why your Binding is failing.

    If the List<int> that you're binding to is the same for every item then maybe you should find another way to bind to it, maybe you could make it static and use StaticResource in the Binding.

    Anyway, to bind ItemsSource to a List<int> property in your source class you can use ElementStyle and ElementEditingStyle (as pointed out by others). The following should work

    <DataGridComboBoxColumn Header="Number of Copies"
                            SelectedItemBinding="{Binding ListAreaItem}">
        <DataGridComboBoxColumn.ElementStyle>
            <Style TargetType="ComboBox">
                <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/>
            </Style>
        </DataGridComboBoxColumn.ElementStyle>
        <DataGridComboBoxColumn.EditingElementStyle>
            <Style TargetType="ComboBox">
                <Setter Property="ItemsSource" Value="{Binding LifeAreaList}"/>
            </Style>
        </DataGridComboBoxColumn.EditingElementStyle>
    </DataGridComboBoxColumn>