您可以通过使用CollectionViewSource
,该包装由WPF控件使用的所有集合的后代这样做。虽然你需要实现IComparer
。这里我用一个辅助类ComparableComparer<T>
它使用IComparable<T>
实现,但你可以把你的逻辑到Foo
类,如果你想要的。
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);
}
}
}
注:
- 的
ComparableComparer<T>
实施是快速和肮脏。它也应该检查空值。
- 您应该使用MVVM模式,而不是代码隐藏。
外部链接: