Page 1 of 1

Passing Dependency object to VisualTreeHelper

Posted: Tue Jan 10, 2017 6:21 am
by Amrutha
Hello Team,

I wanted to pass the DependencyObject's object to the VisualTreeHelper.GetChilderCount() but it is showing error as:
Cannot convert from 'System.Windows.DependencyObject' to 'System.Windows.UIElement'

It was possible to pass these objects in SilverLight Application but in CSHTML5 project I could not.

Sample Code example from SilverLight Application:

public static T FindVisualChildByType<T>(DependencyObject parent) where T : DependencyObject
{
for (int count = 0; count < VisualTreeHelper.GetChildrenCount(parent); count++)
{
var child = VisualTreeHelper.GetChild(parent, count);
}
}

Kindly let me know how to pass the DependencyObject object instead of System.Windows.UIElement.

Regards,
Amrutha

Re: Passing Dependency object to VisualTreeHelper

Posted: Tue Jan 10, 2017 6:36 am
by JS-Support @Userware
Hi,

In the current implementation of CSHTML5, only UIElements can have visual children. In Silverlight, most dependency objects are also UIElements, so this shouldn't be an issue.

Please change your method to:

Code: Select all

public static T FindVisualChildByType<T>(DependencyObject parent) where T : DependencyObject
{
    if (parent is UIElement)
    {
        for (int count = 0; count < VisualTreeHelper.GetChildrenCount((UIElement)parent); count++)
        {
            var child = VisualTreeHelper.GetChild((UIElement)parent, count);
            if (child is T)
            {
                return (T)child;
            }
            else
            {
                var ret = FindVisualChildByType<T>(child);
                if (ret != null)
                    return ret;
            }
        }
    }
    return null;
}


If you need to deal with a DependencyObject that is not a UIElement but still has children that you need to find using the method, please feel free to let me know (in this case, please provide an example).

Thank you.
Regards,
JS-Support