Search code examples
c#wpfdatagriddatagridcomboboxcolumn

Select ComboBox First item in DataGridComboBoxColumn


I want the first item of each combo box to be selected automatically.

<DataGridComboBoxColumn SelectedItemBinding="{Binding Version}" >
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=Versions}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>

    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=Versions}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>

</DataGridComboBoxColumn>

I wrote <Setter Property="SelectedIndex" Value="0" /> on EditingElementStyle & ElementStyle but nothing happened and it doesn't work.


Solution

  • You set a SelectedItemBinding in your XAML, so the selected item is synchronized from your view model and is most likely null. If you remove the binding from your data grid combo box column definitions, this setter works.

    <Setter Property="SelectedIndex" Value="0" />
    

    However, the most simple solution is to keep the selected item binding and set the Version property in your model to the first item in your collection when you assign or populate it.

    Version = Versions[0];
    

    Then the ComboBox will get this item as the selected item and there is no need to add a setter.