1

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

4

1 回答 1

1

selectedItem变量将包含 null,因为该SelectedItem属性不返回 type ListBoxItem。该SelectedItem属性返回一个它从集合中接收到的对象,并提供它的ItemsSource属性。

改成 :-

object selectedItem = lstmenuItems.SelectedItem;

这应该让你更进一步。

也就是说,请考虑ItemsSource绑定到ObservableCollection并操作集合。

于 2010-09-17T12:08:10.740 回答