Accessing the ScrollViewer of a ListBox from C#

前端 未结 6 1667
醉酒成梦
醉酒成梦 2020-12-01 18:26

I\'d like to change the properties of a ScrollViewer of a ListBox from C#.

I found this question here on Stackoverflow. I took the accepted

6条回答
  •  醉梦人生
    2020-12-01 19:02

    you can try this little helper function

    usage

    var scrollViewer = GetDescendantByType(yourListBox, typeof(ScrollViewer)) as ScrollViewer;
    

    helper function

    public static Visual GetDescendantByType(Visual element, Type type)
    {
      if (element == null) {
        return null;
      }
      if (element.GetType() == type) {
        return element;
      }
      Visual foundElement = null;
      if (element is FrameworkElement) {
        (element as FrameworkElement).ApplyTemplate();
      }
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) {
        Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
        foundElement = GetDescendantByType(visual, type);
        if (foundElement != null) {
          break;
        }
      }
      return foundElement;
    }
    

    Hope this helps

提交回复
热议问题