具有空值的组合框 - SelectedItem 绑定
我想要一个包含城市选项的组合框可供选择,其中一个选项是空选项(没有城市)。 itemsource 绑定到“City”对象列表。列表包含空值来表示空选项。 SelectedItem 绑定到“City”类型的属性。除了在组合框中选择空选项的情况之外,一切正常。绑定到 SelectedItem 的属性不会使用 null 值进行更新,而是保留先前的选择。我怎样才能解决这个问题?
谢谢你的解答 格雷格
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是我的经历。我有以下 XAML:
我在代码隐藏中创建了一个名为 Cities 的属性作为 List,并用字符串和空值填充它。
当选择 null 时,SelectedItem 是一个 ComboBoxItem。
在 OnNewCity 中,我根据 SelectedItem 填充另一个文本框,并且看到相同的行为。
您能否提供有关 XAML 和代码的更多信息?
在作者评论后编辑:
谢谢您的 XAML。我使用了相同的一个,使用 City 类而不是字符串列表,我得到了与您相同的行为。 SelectedCity 中的断点显示未调用 setter。
当 City 对象为 null 时,SelectedItem 属性的类型为 ComboBoxItem,因此我的猜测是 WPF 会查找与 ComboBoxItem 类型兼容的 SelectedCity 属性,以便调用 setter。在这种情况下它找不到一个。
我更改了代码隐藏以设置类型对象的 SelectedCity 。在这种情况下,即使对于空城市,也会调用 setter!
我不确定更改 SelectedCity 的类型是一个好方法。类型对象不应该被过度使用。但是您可以拥有另一个仅在绑定(以及类型对象)中使用的属性,该属性在类型检查后正确设置 SelectedCity。
另一个更好的解决方案是考虑将空城市放入绑定列表中是否有意义。您可以删除它,或者有一个特殊的城市,有一个特殊的名称来代表 null 吗?
This is not my experience. I have the following XAML:
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 ?