之前忘记在哪里看到一个获取列表的ScrollViewer的方式,是使用VisualTree遍历子控件集合,从而获取到ScrollViewer
1 public static ScrollViewer GetScrollViewer(DependencyObject parent) 2 { 3 if (parent == null) 4 return null; 5 var count = VisualTreeHelper.GetChildrenCount(parent); 6 7 for (int i = 0; i < count; i++) 8 { 9 var item = VisualTreeHelper.GetChild(parent, i); 10 if (item is ScrollViewer viewer) 11 { 12 return viewer; 13 } 14 else 15 { 16 return GetScrollViewer(item); 17 } 18 } 19 return null; 20 }