我有一个名为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}" />
您查询将返回按键排序的第一个组,您希望它做什么? – 2014-12-04 10:23:30
'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
我不知道什么是错误的,但是如果我插入建议并删除索引为2的条目,则OrderBy函数不起作用 – Stampy 2014-12-04 10:41:09