Search code examples
c#wpfdatagridcomboboxcolumn

Binding in DataGridComboBoxColumn does not work


Why does it work this way :

<DataGridComboBoxColumn Header="Format"
         SelectedItemBinding="{Binding Format, UpdateSourceTrigger=PropertyChanged}"
         ItemsSource="{Binding Source={StaticResource with formatenumvalues}}"
IsReadOnly="False"/>

That's how it works too :

<DataGridTemplateColumn Header="Category">
<DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox ItemsSource="{Binding CategoryList, UpdateSourceTrigger=PropertyChanged}"
                      SelectedItem="{Binding Category, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

But not like this :

<DataGridComboBoxColumn Header="Category"
         SelectedItemBinding="{Binding Category, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         ItemsSource="{Binding CategoryList, UpdateSourceTrigger=PropertyChanged}"
         IsReadOnly="False"/>

Can DataGridComboBoxColumn only work with static resources or is there something else wrong? categoryList here is ObservableCollection, Category is a regular string.

I have tried various binding options provided by neural networks. I also tried to find a similar solution, but none of them helped.


Solution

  • The following code is working:

    <DataGridComboBoxColumn    SelectedValueBinding="{Binding Category, UpdateSourceTrigger=PropertyChanged}">
                        <DataGridComboBoxColumn.ElementStyle>
                            <Style TargetType="{x:Type ComboBox}">
                                <Setter Property="ItemsSource" Value="{Binding CategoryList}"/>
                                <Setter Property="VerticalAlignment" Value="Center"/>
                            </Style>
                        </DataGridComboBoxColumn.ElementStyle>
                        <DataGridComboBoxColumn.EditingElementStyle>
                            <Style TargetType="{x:Type ComboBox}">
                                <Setter Property="ItemsSource" Value="{Binding CategoryList}"/>
                                <Setter Property="VerticalAlignment" Value="Center"/>
                            </Style>
                        </DataGridComboBoxColumn.EditingElementStyle>
                    </DataGridComboBoxColumn>
    

    The "Category" and the "CategoryList" are properties on the item class.