假设我有以下ViewModel:
public class ViewModel
{
public ObservableCollection<Entity> Entities;
public int SelectedEntityId { get; set; }
}
以下XAML:
<ComboBox ItemsSource="{Binding Entities}"
DisplayMemberPath="Name"
SelectedValuePath="Id"
SelectedValue="{Binding SelectedEntityId}" />
有时,需要从数据库中刷新Entities
。在这种情况下,我想将选择保留在组合框中(如果具有所选Id的项目仍然存在于Entities
中)。我怎么能这样做?
要警告,此解决方案不有效:
public void LoadData()
{
int oldId = SelectedEntityId;
repository.Entities.Get()
.OrderBy(e => e.Name)
.ToObservableCollection(Entities); // My extension
SelectedEntityId = oldId;
OnPropertyChanged("SelectedEntityId");
}