Reputation: 109
I have a wpf combo box that is bound to an IEnumerable
collection in my view model. When the combobox is first bound, null is selected. When selecting any other value in the combobox, the null disappears. Is there a way to have the null value remain without altering the collection?
<ComboBox ItemsSource="{Binding CarCollection}" SelectedItem="{Binding SelectedCar}"
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CarName}" VerticalAlignment="Center"
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Upvotes: 2
Views: 195
Reputation: 61339
No, you cannot have null
be an option unless it is actually in the list.
You can of course set the backing property to null
which should clear the UI selection. If you need a null property, without modifying the list in the view model, consider using CompositeCollection
. With it, you can do something like:
<CollectionViewSource x:Key="ComboBoxItems">
<CompositeCollection>
<ListViewItem>Pick a choice</ListViewItem>
<CollectionContainer Source="{Binding MyCollection}"/>
</CompositeCollection>
</CollectionViewSource>
A full example can be found on MSDN.
Upvotes: 2