AspUser7724
AspUser7724

Reputation: 109

WPF combobox binding null value

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

Answers (1)

BradleyDotNET
BradleyDotNET

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

Related Questions