Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Scrolling Event of ListBox?

Is there an event fired when a ListBox begins to scroll?

I currently have the following code to allow for a seamless drag and dropping from a listbox.

<ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" Margin="-5"  />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate >
                    <DataTemplate>

                        <Image  ManipulationStarted="ListImage_ManipulationStarted" Tag="{Binding selfReference}"   x:Name="ListImage" Margin="2.5" Stretch="Fill" Source="{Binding thumbnailURL}" Height="64" Width="64"/>

                    </DataTemplate>
                </ListBox.ItemTemplate>

            </ListBox>

And then in the code

private void ListImage_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            if (dImage == null)
            {
                SoundEffectModel selectedModel = (sender as Image).Tag as SoundEffectModel;
                int newIndex = listBoxSource.Items.IndexOf(selectedModel);
                if (newIndex != -1)
                {
                    listBoxSource.SelectedIndex = newIndex;
                }
            }
        }

I then duplicate the selected item in the listbox, and place it directly over the current location of the selected item. All works well.

However, if the user begins to scroll the listBox instead of draging the item around the application, the duplicated image sits ontop of the listBox and it looks unprofessional. As soon as the user lifts their finger, the duplicated item is deleted, because I can detect the manipulationComplete event, and realize that the item is in the "wrong place".

Is there a way for me to delete the item when the scrolling begins instead of waiting for the manipulationComplete event?


Related questions for context:

like image 847
Bob Avatar asked Nov 05 '22 05:11

Bob


1 Answers

No, there is not an event fired when the ListBox scrolls, however, you can locate the ScrollViewer which is within the ListBox template and handle the ValueChanged event which occurs as soon as scrolling starts.

You can locate the scrollbar as follows:

/// <summary>
/// Searches the descendants of the given element, looking for a scrollbar
/// with the given orientation.
/// </summary>
private static ScrollBar GetScrollBar(FrameworkElement fe, Orientation orientation)
{
  return fe.Descendants()
            .OfType<ScrollBar>()
            .Where(s => s.Orientation == orientation)
            .SingleOrDefault();

}

This uses Linq to Visual Tree, as described in this blog post.

like image 70
ColinE Avatar answered Nov 13 '22 15:11

ColinE