Passing Dependency object to VisualTreeHelper

Please post public support tickets here. Note: for private support tickets, please send an email to support@cshtml5.com instead.
Amrutha
Posts: 21
Joined: Tue Nov 15, 2016 5:10 am

Passing Dependency object to VisualTreeHelper

Postby Amrutha » Tue Jan 10, 2017 6:21 am

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

JS-Support @Userware
Site Admin
Posts: 1093
Joined: Tue Apr 08, 2014 3:42 pm

Re: Passing Dependency object to VisualTreeHelper

Postby JS-Support @Userware » Tue Jan 10, 2017 6:36 am

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


Return to “Technical Support”

Who is online

Users browsing this forum: No registered users and 1 guest