开发者

Silverlight 4 and LisBox's SelectedItem when using DataTemplate as ItemTemplate

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>
           <StackPan开发者_开发知识库el 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜