2

Recently I asked similar questions here and here, but could not fix the issue properly.

I have a DataGrid with ComboBox that can contain either a selected item or not. But if it does then the ComboBox should select it when the dropdown is opening which is doesn't.

ComboBox

Currently I have this code which works except when opening the dropdown the first time. It is nothing selected.

 <DataGridTemplateColumn Header="Company">
     <DataGridTemplateColumn.CellEditingTemplate>
         <DataTemplate>
             <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.Companies}" 
                       SelectedItem="{Binding Company, Converter={StaticResource NullValueConverter}}"/>
         </DataTemplate>
     </DataGridTemplateColumn.CellEditingTemplate>
     <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
         <TextBlock Text="{Binding Company, Converter={StaticResource NullValueConverter}}" />
      </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The NullValueConverter prevents exceptions if the Company is null.

juergen d
  • 201,996
  • 37
  • 293
  • 362

1 Answers1

2
  • If your company was not a string as you mentioned in the comments then it can't display the Name unless you set DisplayMemberPath="Name" or create an ItemTemplate.

  • You should use SelectedItem="{Binding Company,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" to update the value as soon as it changes because if you don't it will only raise ProperyChanged when you focus another cell or row.

  • if your Property was immutable or a value type then you should use SelectedValue="{Binding Path=Company,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" SelectedValuePath="Content"

.

Xi Sigma
  • 2,292
  • 2
  • 13
  • 16
  • 1
    Thanks. Tried your suggestions, but nothing changed. BTW It does display the name without `DisplayMemberPath="Name"` since I implemented `ToString()` in `Company` – juergen d Apr 08 '15 at 20:15
  • 1
    @juergend then nothing is wrong with what you showed and you don't need the null converter, you mean if you open BMW the second row you see nothing selected?! – Xi Sigma Apr 08 '15 at 20:25
  • BTW I had to make sure the `SelectedItem` is one of the `ItemsSource` objects. – juergen d Apr 08 '15 at 21:07
  • @juergend it has to be, but even if you set your SelectedItem to some instance that is not in your ItemsSource you'll get no exception, just no item will be selected – Xi Sigma Apr 08 '15 at 21:12