silverlight 子UserControl获取父UserControl

文章转载自:

[Silverlight] Silverlight中访问父对象

http://bbs.blueidea.com/thread-2964806-1-1.html

当前一个需求是一个UserControl内嵌套了子的UserControl,子需要调用父的里面的方法。

主要用到的代码:

public static class TreeHelper

    {

        public static T FindParentByType<T>(this DependencyObject child) where T : DependencyObject

        {

            Type type = typeof(T);

            DependencyObject parent = VisualTreeHelper.GetParent(child);



            if (parent == null)

            {

                return null;

            }

            else if (parent.GetType() == type)

            {

                return parent as T;

            }

            else

            {

                return parent.FindParentByType<T>();

            }

        }

    }


调用方法:this就是当前对象,找到父UserControl就是RiverPage这个对象

RiverPage parent = this.FindParentByType<RiverPage>();

 

你可能感兴趣的:(silverlight)