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

查看:32
本文介绍了WPF 对 ObservableCollection 进行排序会取消选择 ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ComboBox,用户可以在其中选择他们正在处理的 JobType.ComboBox 有一个 AllJobTypes 列表.问题源于当用户添加新的 JobType 时,我将 JobType 添加到 AllJobTypes ObservableCollection,然后对其进行排序.当排序发生时,组合框会被取消选择,但不确定为什么.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,而不是在视图模型中对集合进行排序,你可以在其中指定一个 <代码>排序描述:

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>

有关更多信息,请参阅如何:使用 XAML 中的视图对数据进行排序和分组

这篇关于WPF 对 ObservableCollection 进行排序会取消选择 ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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