我有一个使用 2 个 DevExpress ListBoxControls 的 winform 应用程序,用户可以将项目从一个移动到另一个。左侧的框具有“所有可用”部分,而右侧的框具有当前分配给用户的内容。我是泛型的新手,但正在尝试在这个项目中实现它们。每个 ListBoxControl 通过它的 DataSource 绑定到一个 ObservableCollection:
ObservableCollection<Sections> allSections = new ObservableCollection<Sections>((dbContext.Sections
.OrderBy(s => s.SectionName).AsEnumerable<Sections>()));
listboxAllSections.DataSource = allSections;
listboxAllSections.DisplayMember = "SectionName";
listboxAllSections.ValueMember = "SectionID";
所以我在每个列表框之间有 4 个按钮,以允许用户来回移动项目:
MoveRight >
MoveAllRight >>
MoveLeft <
MoveAllLeft<<
我创建MoveRight
了MoveLeft
这个通用函数:
private void MoveItem<T>(ListBoxControl source, ListBoxControl target)
{
ObservableCollection<T> sourceItems = (ObservableCollection<T>)source.DataSource;
ObservableCollection<T> targetItems = (ObservableCollection<T>)target.DataSource;
target.BeginUpdate();
//Add items to target.
foreach (T item in source.SelectedItems)
targetItems.Add(item);
//Remove items from source.
for (int x = 0; x < source.SelectedItems.Count; x++)
sourceItems.Remove((T)source.SelectedItems[x]);
target.EndUpdate();
}
一切都很好,但我想为其添加排序。向右移动项目时不需要排序,只有向左移动项目时才需要排序。我不知道如何根据某个属性对通用集合进行排序。例如,Sections
有一个SectionName
我想要排序的属性。如果我使用实际类型,我可以这样做:
ObservableCollection<Sections> sourceItems = (ObservableCollection<Sections>)listboxAllSections.DataSource;
var sortedItems = new ObservableCollection<Sections>();
foreach (var item in sourceItems.OrderBy(t => t.SectionName))
sortedItems.Add(item);
listboxAllSections.DataSource = sortedItems;
但是我不知道如何使这个泛型sourceItems.OrderBy(t => t.SectionName)
成为传入的 Type 的字段。
任何帮助/指导表示赞赏!