views:

66

answers:

1

I would like to have a combobox with cities options to choose, one of the option is an empty option (no city). The itemsource is binded to the List of "City" objects. The List contains null value to represent an empty option. The SelectedItem is binded to a property of "City" type. Everything works except the situation when the empty option is picked in the combobox. The property binded to SelectedItem is not updated with the null value but keeps the previous selection. How could i solve this out?

thank you for asnwer Greg

A: 

This is not my experience. I have the following XAML:

<TextBlock Text="{Binding ElementName=_cbx, Path=SelectedItem}" Margin="20" />
<ComboBox x:Name="_cbx" ItemsSource="{Binding Cities}" HorizontalAlignment="Left" SelectionChanged="OnNewCity" />

I created a properties called Cities in the code-behind as List and filled it with values that are strings and nulls. When null is selected, the SelectedItem is a ComboBoxItem.

In the OnNewCity, I populate another text box based on SelectedItem and I see the same behaviour.

Could you give more info on your XAML and code ?

Edit after author's comment:

Thank you for the XAML. I used the same one, with a City class instead of a list of strings and I get the same behaviour as you do. A breakpoint in SelectedCity shows that the setter is not called. When the City object is null, the SelectedItem property is of type ComboBoxItem and thus my guess is that WPF looks for a SelectedCity property of a type compatible with ComboBoxItem in order to call the setter. It cannot find one in this case. I changed my code-behind to set SelectedCity of type object. In this case, the setter is called, even for a null city!

I am not sure that changing the type of SelectedCity is a good way to go. Type object should not be overused. But you could have another property used only in binding (and of type object) that sets the SelectedCity correctly after type checking.

Another, better solution is to consider whether it makes sense to put a null city in a bound list. Could you remove this or have a special city with a special name that would represent null ?

Timores
<ComboBox ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity, Mode=TwoWay}" /> here is the way i use it, Cities is list of objects of customer type "City" plus null value and property SelectedCity is also type "City"
Greg