2010-05-28 242 views

回答

3

這是如此的痛苦得到工作:

HitTestResult hitTest = VisualTreeHelper.HitTest(SoundListView, new Point(5, 5)); 
System.Windows.Controls.ListViewItem item = GetListViewItemFromEvent(null, hitTest.VisualHit) as System.Windows.Controls.ListViewItem; 

和函數來獲取列表item:

System.Windows.Controls.ListViewItem GetListViewItemFromEvent(object sender, object originalSource) 
    { 
     DependencyObject depObj = originalSource as DependencyObject; 
     if (depObj != null) 
     { 
      // go up the visual hierarchy until we find the list view item the click came from 
      // the click might have been on the grid or column headers so we need to cater for this 
      DependencyObject current = depObj; 
      while (current != null && current != SoundListView) 
      { 
       System.Windows.Controls.ListViewItem ListViewItem = current as System.Windows.Controls.ListViewItem; 
       if (ListViewItem != null) 
       { 
        return ListViewItem; 
       } 
       current = VisualTreeHelper.GetParent(current); 
      } 
     } 

     return null; 
    } 
3

在試圖找出類似的東西之後,我想我會我的結果在這裏(因爲它似乎比其他反應更容易):

簡單的能見度測試我從here得到。

private static bool IsUserVisible(FrameworkElement element, FrameworkElement container) 
{ 
    if (!element.IsVisible) 
     return false; 

    Rect bounds = 
     element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight)); 
    var rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight); 
    return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight); 
} 

之後,您可以遍歷listboxitems並使用該測試來確定哪些是可見的。由於listboxitems總是按照相同的順序排列,因此列表中的第一個可見列表項將成爲用戶的第一個可見列表項。

private List<object> GetVisibleItemsFromListbox(ListBox listBox, FrameworkElement parentToTestVisibility) 
{ 
    var items = new List<object>(); 

    foreach (var item in PhotosListBox.Items) 
    { 
     if (IsUserVisible((ListBoxItem)listBox.ItemContainerGenerator.ContainerFromItem(item), parentToTestVisibility)) 
     { 
      items.Add(item); 
     } 
     else if (items.Any()) 
     { 
      break; 
     } 
    } 

    return items; 
} 
2

我們只有計算偏移我們的列表框,並且第一個可見項目將是該指數等於VerticalOffset在項目......

 // queue is the name of my listbox 
     VirtualizingStackPanel panel = VisualTreeHelper.GetParent(queue.Items[0] as ListBoxItem) as VirtualizingStackPanel; 
     int offset = (int)panel.VerticalOffset; 
     // then our desired listboxitem is: 
     ListBoxItem item = queue.Items[offset] as ListBoxItem; 

希望這有助於你。 。 。!

+1

我收到錯誤:'發生了'System.InvalidCastException'類型的未處理異常。 我認爲它出現在鑄造listBox.Items [0] – thowa 2015-12-20 16:24:22

+0

我想它不起作用的情況下分組,但否則它是fastes方式(到目前爲止) – SnowballTwo 2016-08-15 13:05:29

相關問題