EF ComboBox不显示SelectedItem绑定 [英] EF ComboBox not displaying SelectedItem Binding

查看:77
本文介绍了EF ComboBox不显示SelectedItem绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework和Caliburn.Micro来实现MVVM应用程序.

I am using Entity Framework and Caliburn.Micro to implement an MVVM application.

基本上,我已经建立了一对多关系的AuthorModel和BookModel-一个拥有多本书的Author和一个只有一个Author的Book.

Basically, I have set up AuthorModel and BookModel in a one to many relationship - an Author having multiple Books and a Book having only a single Author.

我有一个SelectBookWindow,在其中使用DbContext加载ObservableCollection<Book>,从中选择要查看/编辑的书.然后,我将所选的Book作为参数传递给EditBookWindow,在其中我有一个组合框,枚举了所有Authors,但选择了当前的Author.

I have a SelectBookWindow where I use DbContext to load ObservableCollection<Book>, from where I select a Book I want to view/edit. I then pass the selected Book as a parameter to an EditBookWindow where I have a combobox enumerating all the Authors but with the current Author selected.

在这里,我使用不同的DbContext实例加载ObservableCollection<Author>并将其设置为组合框的ItemsSourceSelectedItem="{Binding Author}". (AuthorBook的虚拟属性)

In here, I load up ObservableCollection<Author> using a different instance of DbContext and set it as the combobox's ItemsSource and as well as do SelectedItem="{Binding Author}". (Author being a virtual property of Book)

组合框正确显示作者列表.但是,它似乎没有显示书的作者"作为其SelectedItem.

The ComboBox displays the Author list correctly. However, it doesn't seem to display the Book's Author as its SelectedItem.

这是因为我使用的是DbContext的其他实例吗?如果是这样,我该如何解决这个问题?

Is this because I am using a different instance of DbContext? If so, how can I rectify this problem?

推荐答案

是的.尽管内容与绑定到SelectedItem的内容相同,但是ItemsSource中的作者引用的是另一个对象.

Yes it is. Because the author in ItemsSource is referencing to a different object although the content is the same as the one that is bind to SelectedItem.

我对EF知之甚少,我想您可以为两个实体使用相同的上下文.或重写Author类的equals(和gethashcode)以比较内容,如果相同,则返回true.

I don't know much about EF, I guess you can use the same context for the two entities. Or override the equals (and gethashcode) of the Author class to compare the content then return true if the same.

这篇关于EF ComboBox不显示SelectedItem绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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