Reputation: 353
There are many samples on how to move ListBoxItem
up or down - but only if ListBox.ItemsSource
type is known.
Can anyone help share some more generic code, if ListBox.ItemsSource
type is simply IEnumerable
?
I need such code to move ListBoxItem
up/down, regardless if ItemsSource
was set in XAML, code-behind or ViewModel. In the latter case it will, most likely, be an ObservableCollection
.
Upvotes: 0
Views: 199
Reputation: 31616
Just cast the list into objects. Here is an example that takes the last item and moves it to the first item during a double click event:
private void LbFiles_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var sourceList = lbFiles.ItemsSource
.OfType<object>()
.ToList();
var moveLast = sourceList[sourceList.Count - 1];
sourceList.RemoveAt(sourceList.Count - 1);
var newList = new List<object>() { moveLast };
newList.AddRange(sourceList);
lbFiles.ItemsSource = newList;
}
XAML
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<x:Array x:Key="FileNames" Type="system:String">
<system:String>C:\Temp\Alpha.txt</system:String>
<system:String>C:\Temp\Beta.txt</system:String >
<system:String>C:\Temp\Gamma.txt</system:String >
</ x:Array >
</ StackPanel.Resources >
<ListBox Name = "lbFiles"
ItemsSource = "{StaticResource FileNames}"
MouseDoubleClick = "LbFiles_MouseDoubleClick"
Margin = "10" />
</ StackPanel >
Here it is in action
Upvotes: 1