Vous pouvez le faire en utilisant CollectionViewSource
, dont les descendants enveloppent toutes les collections utilisées par les contrôles WPF. Cependant, vous devrez implémenter IComparer
. Ici, j'utilise une classe d'assistance ComparableComparer<T>
qui utilise l'implémentation IComparable<T>
, mais vous pouvez mettre votre logique dans la classe Foo
si vous le souhaitez.
MainWindow.xaml
<Window x:Class="So16368719.MainWindow" x:Name="root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListView ItemsSource="{Binding FooItemsSource, ElementName=root}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Data;
namespace So16368719
{
public partial class MainWindow
{
public ObservableCollection<Foo> FooItems { get; set; }
public ListCollectionView FooItemsSource { get; set; }
public MainWindow()
{
FooItems = new ObservableCollection<Foo> {
new Foo("a"), new Foo("bb"), new Foo("ccc"), new Foo("d"), new Foo("ee"), new Foo("ffff")
};
FooItemsSource = (ListCollectionView)CollectionViewSource.GetDefaultView(FooItems);
FooItemsSource.CustomSort = new ComparableComparer<Foo>();
InitializeComponent();
}
}
public class Foo : IComparable<Foo>
{
public string Name { get; set; }
public Foo (string name)
{
Name = name;
}
public int CompareTo (Foo other)
{
return Name.Length - other.Name.Length;
}
}
public class ComparableComparer<T> : IComparer<T>, IComparer
where T : IComparable<T>
{
public int Compare (T x, T y)
{
return x.CompareTo(y);
}
public int Compare (object x, object y)
{
return Compare((T)x, (T)y);
}
}
}
Note:
- La mise en œuvre de
ComparableComparer<T>
est rapide et sale. Il devrait également vérifier les nulls.
- Vous devez utiliser le modèle MVVM et non le code-behind.
Liens externes: