Wpf,在ComboBox中保持选择

时间:2015-10-17 19:21:59

标签: c# wpf mvvm combobox selection

假设我有以下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");
}

0 个答案:

没有答案