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
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))