我使用的是wpf和MVVM模式。我需要将我的comboboxedit ItemsSource绑定到User类的集合。它包含Employee字段,其中包含字符串FullName字段。我需要将选定的FullName值绑定到我的ViewModel中的另一个对象的字符串Field(Document-> UserFullName)。我怎么能这样做。
答案 0 :(得分:0)
如果我理解正确,您将ComboBox绑定到用户实例列表。 User类具有Employee类型的属性,而Employee类具有名为FullName的类型为string的属性。 viewmodel还有一个Document类型的属性,Document类有一个名为UserFullName的属性,类型为string。在ComboBox中选择值(用户)时,要将FullName(User.Employee.FullName)的值设置为Document(Document.UserFullName)的UserFullName属性。
正确?
如果这是您唯一想要做的事情,也许最简单的解决方案可能是不将ComboBox绑定到User-instances集合,而是绑定到一组字符串,这些字符串是这些用户的FullName(来自Employee)。只需迭代您的用户列表就不会难以创建该集合。如果将ComboBox绑定到字符串集合,那么您应该能够将ComboBox的SelectedValue直接绑定到Document的DocumentFullName(Document.UserFullName)。
另一种解决方案是在viewmodel中拥有User类型的属性“SelectedUser”,并将ComboBox的SelectedValue绑定到此。每当这个更改的值你也设置Document.UserFullName的值,如下所示:
private User _selectedUser;
public User SelectedUser
{
get
{
_return _selectedUser;
}
set
{
if (value != _selectedUser)
{
_selectedUser = value;
Document.UserFullName = _selectedUser.Employee.FullName;
OnPropertyChanged("SelectedUser");
}
}
}