Blog Archive

Thursday, August 28, 2014

Set property value without reference types

Including Reference could mess up code (e.g circulare refernce or DI failure). So use reflection while walk up down logical tree will fix that. In fact, runtime type resolution in dynamic language does just that.
        void SetPropertyOfAncestor(FrameworkElement framewkElement, string AncestorTypeName,string propName, object propValue)
        {
            FrameworkElement current = VisualTreeHelper.GetParent(framewkElement) as FrameworkElement;
            while (current != null)
            {
                Type t = current.GetType();
                if (t.Name == AncestorTypeName)
                {
                    PropertyInfo pi = t.GetProperty(propName);
                    if (pi != null)
                    {
                        pi.SetValue(current, propValue, null);
                        return;
                    }
                    else
                    {
                        current = VisualTreeHelper.GetParent(current) as FrameworkElement;
                    }
                }
                else
                {
                    current = VisualTreeHelper.GetParent(current) as FrameworkElement;
                }
            }
        }

No comments: