locked
How to get a reference to object RRS feed

  • Question

  • Hi!

    I have in xaml:

    <Grid>

    <Border>

    <Frame>
    .....
    </Frame>

    </Border>

    <MyClass>
    ...
    </MyClass>

    <Grid>

     

    In the MyClass class code behind I need to get a reference to Frame class which is above so that I can use Navigated event from it.

    How could I get the reference? Please help.

     

    cheers

    pete

     

    Monday, March 14, 2011 9:36 AM

Answers

  • You can use this extension Method to search up the Visual Tree...

    public static DependencyObject FindParentByName(this FrameworkElement startPoint, string elementName)
            {
                DependencyObject returnValue = null;
                if (startPoint != null)
                {
                    var parent = VisualTreeHelper.GetParent(startPoint);
                    if (parent != null)
                    {
                        var fe = parent as FrameworkElement;
                        if (fe != null)
                        {
                            if (fe.Name == elementName)
                            {
                                returnValue = fe;
                            }
                            else
                            {
                                returnValue = fe.FindParentByName(elementName);
                            }
                        }
                        else
                        {
                            returnValue = fe.FindParentByName(elementName);
                        }
                    }
                }
                return returnValue;
            }

    Usage:

    using <namepspace where you added the extension method>;

    myClassObj.FindParentByName("<xNameofFrame>");

    Hope That Helps

    Monday, March 14, 2011 9:57 AM