我有以下代码:
SubjectsToChooseFrom = new ObservableCollection<SubjectDTO>(_model.Subjects);
SubjectsToChooseFrom = SubjectsToChooseFrom.Where(x => x.Id == (int)CurrentProgId);
SubjectsToChooseFrom
绑定到ComboBox
。在此之后,框中只显示一个元素而不是列表。为什么会这样,以及如何确保x.Id == (int)CurrentProgId
中的所有值都保留在SubjectsToChooseFrom
?
更新
XAML和所要求的代码:
<ComboBox Text="Choose program" Margin="5" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding SubjectsToChooseFrom}"
SelectedValue="{Binding CurrentSubjectId, Mode=TwoWay}"
SelectedValuePath="Id"
DisplayMemberPath="SubjectName">
</ComboBox>
声明:
private IEnumerable<SubjectDTO> _subjectsToChooseFrom;
public IEnumerable<SubjectDTO> SubjectsToChooseFrom
{
get
{
return _subjectsToChooseFrom;
}
set
{
_subjectsToChooseFrom = value;
OnPropertyChanged();
}
}
答案 0 :(得分:0)
Where
会返回IQueryable
。您需要使用ToList()
或ToArray()
等来实现此查询的结果。
如果您正在使用MVVM,那么更好的方法是将您的集合公开为公共属性,并在这些集合因任何原因发生更改时引发PropertyChanged
。然后,您可以将ComboBox绑定到这些属性,它们将自动更新。
答案 1 :(得分:-2)
我最终手工做到了这一点:
await _model.LoadAsync();
SubjectsToChooseFrom = new ObservableCollection<SubjectDTO>(_model.Subjects);
ObservableCollection<SubjectDTO> temp = new ObservableCollection<SubjectDTO>();
foreach (var subject in SubjectsToChooseFrom) {
if(subject.ProgId == CurrentProgId)
{
temp.Add(subject);
}
}
SubjectsToChooseFrom = temp;