视图有一个组合框,其中ObservableCollection<Vendor>
作为源,SelectedItem
绑定到ViewModel中定义的Contact
。尽管在ViewModel的构造函数中成功地为Contact
赋值,但在加载视图时没有显示任何内容。
视图
<ComboBox Grid.Row="0" Grid.Column="2"
ItemsSource="{Binding Vendors}"
SelectedItem="{Binding Contact.Vendor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Id" SelectedValuePath="Key"
IsSynchronizedWithCurrentItem="True"
IsEditable="True" />
视图模型
private ObservableCollection<Vendor> vendors;
public ObservableCollection<Vendor> Vendors
{
get
{
if(vendors == null)
{
vendors = new ObservableCollection<Vendor>(_contactsRepository.GetVendors());
}
return vendors;
}
set
{
if (vendors == value) return;
vendors = value;
OnPropertyChanged();
}
}
private Contact contact;
public Contact Contact
{
get
{
if(contact == null)
{
contact = new Contact();
}
return contact;
}
set
{
if (contact == value) return;
contact = value;
OnPropertyChanged();
}
}
public ModContactViewModel(ContactsRepository contactsRepository, bool isEditing, Contact contact)
{
_contactsRepository = contactsRepository;
IsEditing = isEditing;
Contact = contact;
}
接触模型
public class Contact : ObservableObject
{
private Vendor vendor;
public Vendor Vendor
{
get
{
return vendor;
}
set
{
if (vendor == value) return;
vendor = value;
OnPropertyChanged();
}
}
private string contactId;
public string ContactId
{
get
{
return contactId;
}
set
{
if (contactId == value) return;
contactId = value;
OnPropertyChanged();
}
}
private string contactEmail;
public string ContactEmail
{
get
{
return contactEmail;
}
set
{
if (contactEmail == value) return;
contactEmail = value;
OnPropertyChanged();
}
}
private string comments;
public string Comments
{
get
{
return comments;
}
set
{
if (comments == value) return;
comments = value;
OnPropertyChanged();
}
}
}
供应商模型
public class Vendor : ObservableObject
{
private int key;
public int Key
{
get
{
return key;
}
set
{
if (key == value) return;
key = value;
OnPropertyChanged();
}
}
private string id;
public string Id
{
get
{
return id;
}
set
{
if (id == value) return;
id = value;
OnPropertyChanged();
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
if (name == value) return;
name = value;
OnPropertyChanged();
}
}
}
1条答案
按热度按时间ds97pgxw1#
您的问题是
Contact
对象持有的Vendor
类的特定示例不在源集合中。您可以将
Contact
的Vendor
属性设置为集合中实际存在的示例。或者,您可以重写
Vendor
类的Equals
方法,以定义如果两个Vendor
对象具有相同的Id
,则它们被视为相等: