views:

100

answers:

1

Hi All,

I'm using tow listboxes for drag n drop where user can drag items from source listbox and drop on the target. I'm using a DataTemplate for the ListBoxItems of my ListBox Controls.

I need to give the user ability to move up/down items in the target listbox after they been moved from source. I have two button "Move Up" & "Move Down" to do that but when the user clicks on one of the button, it returns me the null object as selectedItem.

here is my code

private void moveUp_Click(object sender, RoutedEventArgs e)
    {
      ListBoxItem selectedItem = lstmenuItems.SelectedItem as ListBoxItem;

        if (selectedItem != null)
        {
         int index = lstmenuItems.Items.IndexOf(selectedItem);


            if (index != 0)
            {
                lstmenuItems.Items.RemoveAt(index);
                index -= 1;
                lstmenuItems.Items.Insert(index, selectedItem);
                lstmenuItems.SelectedIndex = index;
            }

        }

    } 

I'm sure its to do with the ItemTemplate. here is the xaml for listbox

 <ListBox x:Name="lstmenuItems" Height="300" MinWidth="200" >
    <ListBox.ItemTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal">
                  <StackPanel Orientation="Vertical">
                      <TextBlock Text="{Binding Code}"/>
                      <TextBlock Text="{Binding RetailPrice, StringFormat=£\{0:n\}}" />
                  </StackPanel>
           <!-- Product Title-->
           <TextBlock Text="{Binding Description1}" Width="100"  Margin="2" />
           </StackPanel>
      </DataTemplate>
  </ListBox.ItemTemplate>

Any ideas how can I access the selected Item and how can I move it up/down?

Thanks in advance

+1  A: 

The selectedItem variable will contain a null because the SelectedItem property doesn't return the type ListBoxItem. The SelectedItem property returns an object it received from the collection supply its ItemsSource property.

Change to :-

object selectedItem = lstmenuItems.SelectedItem;

and that should get you a little further.

That said consider having the ItemsSource bound to an ObservableCollection and manipulate the collection instead.

AnthonyWJones
I have binded it to ObeservableCollection but the problem is that its not sorted. so what I want is to go thru the collections at drop event and sort it by the order user dropped into the lists.
Jhelumi
@Jhelumi: If you manipulate the ObservableCollection (rather than the ListBox that is bound to it) the ListBox should change to reflect the changes in the collection.
AnthonyWJones