2013-05-03 53 views
1

我正在寻找一种将ListViewDataSource属性绑定到IComparable自定义对象的集合(任意集合)的智能方法。我想有一个控制实时响应我收藏的变化,并有结果(ListView)排序使用接口方法提供。将ListView绑定到集合IComparable

我想可以通过创建继承自ObservableCollection<T>SortedSet<T>的定制集合并绑定到这样的类(它结合了两者的优点)来完成。我是新来WPF绑定和搜索任何提示。

回答

0

您可以通过使用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模式,而不是代码隐藏。

外部链接: