WPF对ObservableCollection进行排序会取消选择ComboBox [英] WPF Sorting an ObservableCollection de-selects a ComboBox

查看:266
本文介绍了WPF对ObservableCollection进行排序会取消选择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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆