2014-12-04 41 views
1

我有一个名为TestList的ObservableCollection<KeyValuePair<int, String>>()绑定在一个Textbox上,我想通过int对收集进行排序。我尝试了以下方法,但它并未对收集进行排序:如何排序ObservableCollection <KeyValuePair <int, string>

new ObservableCollection<KeyValuePair<int, string>>(
       TestList .Where(p => p.Key > 0) 
       .GroupBy(p => p.Key) 
       .Select(grp => grp.First()) 
       .OrderBy(p => p.Key) 
       ); 

如何对收集进行排序?绑定仍然有效吗?

EDIT(没有工作过):

public ObservableCollection<KeyValuePair<int, String>> TestList 
{ 
    get { return testList; } 
    set { 
     testList = value; 
     NotifyPropertyChanged("TestList"); 
    } 
} 

public void Test(int index) 
{ 
    TestList.RemoveAt(index); 
    TestList = new ObservableCollection<KeyValuePair<int, string>>(TestList.OrderBy(p => p.Key)); 
} 

和GUI:

<TextBox Grid.Column="0" IsReadOnly="True" 
Text="{Binding Path=Value , Mode=OneWay}" /> 
+0

您查询将返回按键排序的第一个组,您希望它做什么? – 2014-12-04 10:23:30

+0

'TestList.RemoveAt(index);'将调用getter而不是setter,所以'NotifyPropertyChanged(“TestList”)'不会被调用。如果要在收集更改时通知,请将事件连接到CollectionChanged事件。 'TestList.OrderBy(p => p.Key);''返回一个新的已排序的'IEnuemrable >',这是你丢弃的,它不会改变列表的位置。你需要像'TestList = new ObservableCollection >(TestList.OrderBy(p => p.Key));''来代替。 – 2014-12-04 10:37:15

+0

我不知道什么是错误的,但是如果我插入建议并删除索引为2的条目,则OrderBy函数不起作用 – Stampy 2014-12-04 10:41:09

回答

5

您不必通过做一团。你只需要一个简单的命令。

TestList.OrderBy(p => p.Key) 
+0

我已经在行后设置了一个断点,我的集合没有排序,Property TestList没有被触发。我用一些代码更新了我的问题 – Stampy 2014-12-04 10:30:01

+0

@Stampy Christos的意思是:'TestList = new ObservableCollection >(TestList.OrderBy(p => p.Key));' – franssu 2014-12-04 10:48:28

+0

是的,我试过并设置该行后面的断点,但键(索引)的顺序错误。如果我删除第二个项目(索引1),我得到的收集键(0,2,3,4),但我需要0,1,2,3 – Stampy 2014-12-04 10:50:31

1

由于您的源包含KeyValuePair对象,你可能会认为密钥已重复数据删除。因此,分组没有用处。只要保持OrderBy和可能您的Where,你应该没问题。

new ObservableCollection<KeyValuePair<int, string>>(
      TestList.Where(p => p.Key > 0) 
      .OrderBy(p => p.Key) 
      ); 
相关问题