WPF - 组合框 SelectedItem 未设置? [英] WPF - Combobox SelectedItem not getting set?

查看:28
本文介绍了WPF - 组合框 SelectedItem 未设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ComboBox,它的 ItemsSource 绑定到一个静态的 List 选项.ComboBox 是绑定到 CustomObject 类的表单的一部分,该类的属性之一是 CustomSettingProperty.

I have a ComboBox that has its ItemsSource bound to a static List<CustomSettings> of options. The ComboBox is part of a form which is bound to a CustomObject class, and one of the properties on that class is a CustomSettingProperty.

我想将 ComboBox 的 SelectedItem 绑定到 CustomObject 中指定的属性,但是 SelectedItem="{Binding Path=CustomSettingProperty}" 没有设置默认的选定项.使用断点我可以看到它正在调用 get; 方法,所以我认为问题可能在于 CustomSettingProperty 是与 List 分开创建的,所以WPF 不认为这是同一个项目.

I would like to bind the SelectedItem of the ComboBox to the property specified in the CustomObject, however SelectedItem="{Binding Path=CustomSettingProperty}" is not setting the default selected item. Using breakpoints I can see that it is calling the get; method, so I think the problem might be in the fact the CustomSettingProperty is created separately from the List<CustomObject> so WPF does not think it is the same item.

有没有简单的方法可以做到这一点?或者也许是因为 CustomSettings 类确实包含一个 Id 的替代方法?

Is there an easy way to do this? Or perhaps an alternative since the CustomSettings class does contain an Id?

推荐答案

如果选择的项目与 List 中包含的实例不同,则必须重写 CustomObject 中的 Equals() 以让 ComboBox 知道它是同一个对象.

If the item that is selected is not the same instance that is contained in the List, you must override Equals() in the CustomObject to let the ComboBox know that it is the same object.

如果是同一个实例,也许只是简单的事情,比如将 BindingMode 设置为 TwoWay:

If it's the same instance, maybe it's only a simple thing such as setting the BindingMode to TwoWay:

SelectedItem="{Binding Path=CustomSettingProperty,Mode=TwoWay}"

这篇关于WPF - 组合框 SelectedItem 未设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆