检测ListBox的滚动事件

本文关键字:事件 滚动 ListBox 检测 | 更新日期: 2023-09-27 18:24:16

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>

然后在代码中

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;
                }
            }
        }

然后,我在列表框中复制所选项目,并将其直接放置在所选项目的当前位置上。一切都很好。

但是,如果用户开始滚动listBox,而不是在应用程序中拖动项目,则复制的图像会位于listBox的顶部,看起来不专业。用户一抬起手指,重复的项目就会被删除,因为我可以检测到manipulationComplete事件,并意识到该项目位于"错误的位置"。

有没有办法让我在滚动开始时删除项目,而不是等待manipulationComplete事件?


上下文相关问题:

检测ListBox的滚动事件

否,当ListBox滚动时不会触发事件,但是,您可以定位ListBox模板中的ScrollViewer,并处理滚动开始时发生的ValueChanged事件。

您可以如下定位滚动条:

/// <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();
}

这使用了LinqtoVisualTree,如本文所述。