Reputation: 1726
I've got a winform app that uses 2 DevExpress ListBoxControls that a user can move items from one to the other. The box on the left has "All available" Sections while the box on the right has what's currently assigned to the user. I am new to Generics but am trying to implement them in this project. Each ListBoxControl is bound to an ObservableCollection via it's DataSource:
ObservableCollection<Sections> allSections = new ObservableCollection<Sections>((dbContext.Sections
.OrderBy(s => s.SectionName).AsEnumerable<Sections>()));
listboxAllSections.DataSource = allSections;
listboxAllSections.DisplayMember = "SectionName";
listboxAllSections.ValueMember = "SectionID";
So I have 4 buttons in between each listbox to allow the user to move items back and forth:
MoveRight >
MoveAllRight >>
MoveLeft <
MoveAllLeft <<
For MoveRight
and MoveLeft
I created this Generic function:
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();
}
All works great, but I would like to add sorting to it. I don't need sorting when moving items to the right, only when moving items to the left. I can't figure out how to sort a generic collection based on a certain property. For instance, Sections
has a property called SectionName
that I'd like to sort on. I can do this if I use the actual type:
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;
But I don't know how to make this generic to that sourceItems.OrderBy(t => t.SectionName)
can be the field of the Type that's passed in.
Any help/guidance is appreciated!
Upvotes: 2
Views: 532
Reputation: 1
I guess you should try using a CollectionViewSource
to sort data in your ListBox
. This way you do not have to keep the data sorted in the ObservableCollection
. Besides, it separates your code-behind / ViewModel from the presentation logic.
There is an example showing how to use a CollectionViewSource on MSDN.
Upvotes: 0
Reputation: 11277
you could do this:
private void MoveItem<T>(ListBoxControl source, ListBoxControl target)
where T : IComparable
{
var sortedItems = new ObservableCollection<T>();
var sordet = sourceItems.OrderBy(t => t);
}
if T
knows how to compare it self against anything, you can call List<T>.OrderBy(c => c)
(<-- pseudo code) and you will always have a sorted list.
Upvotes: 1