Combobox with null value - SelectedItem binding

自古美人都是妖i 提交于 2019-12-11 04:18:30

问题


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


回答1:


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 ?



来源:https://stackoverflow.com/questions/2370375/combobox-with-null-value-selecteditem-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!