WPF对ObservableCollection进行排序会取消选择ComboBox [英] WPF Sorting an ObservableCollection de-selects a ComboBox
问题描述
我有一个ComboBox,用户可以在其中选择他们正在处理的JobType. ComboBox具有AllJobTypes列表.问题源于当用户添加新的JobType时,我将JobType添加到AllJobTypes ObservableCollection中,然后对其进行排序.当排序发生时,ComboBox会被取消选择,并且不确定原因. JobConfig.SelectedJobType.Name在此过程中永远不会更改.有没有办法在不破坏ComboBox的情况下对可观察的集合进行排序?
I have a ComboBox where a user can select what JobType they are working on. The ComboBox has a list of AllJobTypes. The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it. When the sorting happens the ComboBox get's de-selected and not really sure why. The JobConfig.SelectedJobType.Name never changes in this process. Is there a way to sort an observable collection where it doesn't break the ComboBox?
public class JobTypeList : ObservableCollection<JobType> {
public void SortJobTypes() {
var sortableList = new List<JobType>(this);
sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
//this works but it creates a bug in the select for JobTypes
for (int i = 0; i < sortableList.Count; i++) {
this.Move(this.IndexOf(sortableList[i]), i);
}
}
在XAML中
<ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
Name="JobTypeComboBox"
ItemsSource="{Binding Path=AllJobTypes}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />
推荐答案
您应该将ComboBox的ItemsSource绑定到CollectionViewSource
,而不是在视图模型中对集合进行排序,您可以在其中指定SortDescription
:>
Instead of sorting the collection in the view model, you should bind the ComboBox's ItemsSource to a CollectionViewSource
, where you can specify a SortDescription
:
<Window ...
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
...>
<Window.Resources>
<CollectionViewSource x:Key="cvs" Source="{Binding AllJobTypes}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Name"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
...
<ComboBox ItemsSource="{Binding Source={StaticResource cvs}}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding JobConfig.SelectedJobType.Name}"/>
...
</Window>
For further information see How to: Sort and Group Data Using a View in XAML
这篇关于WPF对ObservableCollection进行排序会取消选择ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!