2014-12-04 119 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) 
      ); 
相關問題