Accessing the ScrollViewer of a ListBox from C#

前端 未结 6 1665
醉酒成梦
醉酒成梦 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:09

    I've modified the great answer of @punker76 to create an extension method for Visual and provide explicit return type:

       public static class Extensions
       {
          public static T GetDescendantByType(this Visual element) where T:class
          {
             if (element == null)
             {
                return default(T);
             }
             if (element.GetType() == typeof(T))
             {
                return element as T;
             }
             T foundElement = null;
             if (element is FrameworkElement)
             {
                (element as FrameworkElement).ApplyTemplate();
             }
             for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
             {
                var visual = VisualTreeHelper.GetChild(element, i) as Visual;
                foundElement = visual.GetDescendantByType();
                if (foundElement != null)
                {
                   break;
                }
             }
             return foundElement;
          }
    
       }
    

    You can now call it by SomeVisual.GetDescendantByType and it returns either already a correct typed ScrollViewer or null (which is default(T))

提交回复
热议问题