仅在XAML中对组合框进行排序

Dav*_*ave 24 sorting wpf xaml combobox

我很惊讶在此之前没有人问这个......好吧,至少我在这里或其他地方找不到答案,实际上.

我有一个与ObservableCollection数据绑定的ComboBox.一切都很好,直到那些人想要内容排序.没问题 - 我最终改变了简单的属性:

public ObservableCollection<string> CandyNames { get; set; } // instantiated in constructor
Run Code Online (Sandbox Code Playgroud)

对于这样的事情:

private ObservableCollection<string> _candy_names; // instantiated in constructor
public ObservableCollection<string> CandyNames
{
    get {
        _candy_names = new ObservableCollection<string>(_candy_names.OrderBy( i => i));
        return _candy_names;
    }
    set {
        _candy_names = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

这篇文章真的有两个问题:

  1. 如何在XAML中对字符串的简单ComboBox进行排序.我已经研究了这个,只能找到有关SortDescription类的信息,这是我能找到的最接近的实现,但它不适用于ComboBox.
  2. 一旦我在代码隐藏中实现了排序,我的数据绑定就被打破了; 当我向ObservableCollection添加新项目时,ComboBox项目没有更新!我没有看到发生了什么,因为我没有为我的ComboBox指定一个名称并直接操作它,这通常会打破绑定.

谢谢你的帮助!

Wal*_*mer 17

您可以使用CollectionViewSource在XAML中进行排序,但是如果底层集合发生更改,则需要刷新它的视图.

XAML:

<Window x:Class="CBSortTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    Height="300" Width="300">

    <Window.Resources>
        <CollectionViewSource Source="{Binding Path=CandyNames}" x:Key="cvs">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>

    </Window.Resources>
    <StackPanel>
        <ComboBox ItemsSource="{Binding Source={StaticResource cvs}}" />
        <Button Content="Add" Click="OnAdd" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:

using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;

namespace CBSortTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            CandyNames = new ObservableCollection<string>();

            OnAdd(this, null);
            OnAdd(this, null);
            OnAdd(this, null);
            OnAdd(this, null);

            DataContext = this;

            CandyNames.CollectionChanged += 
                (sender, e) =>
                {
                    CollectionViewSource viewSource =
                        FindResource("cvs") as CollectionViewSource;
                    viewSource.View.Refresh();
                };
        }

        public ObservableCollection<string> CandyNames { get; set; }

        private void OnAdd(object sender, RoutedEventArgs e)
        {
            CandyNames.Add("Candy " + _random.Next(100));
        }

        private Random _random = new Random();
    }
}
Run Code Online (Sandbox Code Playgroud)