Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')

like image 806
Night Walker Avatar asked Aug 13 '11 12:08

Night Walker


2 Answers

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>
like image 177
Fredrik Hedblad Avatar answered Sep 20 '22 13:09

Fredrik Hedblad


You are not supposed to set the ItemsSource in the style, the column itself has such a property which may override anything you may try to set in the style. Further, you try to set it in the wrong style (that style is for the display mode), you could try setting it in the EditingElementStyle instead, but i would not recommend that either.

like image 33
H.B. Avatar answered Sep 19 '22 13:09

H.B.