1
Vote

VisualStateManager cannot be used on a Window

description

The functions GetTemplateRoot and GetTemplatedParent of the class VisualStateManager don't take the Window class in account. Here is a modified version.
 
/// <summary>
    ///     Returns the root element of an expanded template for a given control.
    /// </summary>
    private static FrameworkElement GetTemplateRoot(Control control)
    {
        UserControl userControl = control as UserControl;
        if (userControl != null)
        {
            // If using a UserControl, the states will be specified on the
            // root of the content instead of the root of the template.
            return userControl.Content as FrameworkElement;
        }
        else
        {
            // If using a Window, the states will be specified on the
            // root of the content instead of the root of the template.
            Window win = control as Window;
            if (win != null)
            {
                return win.Content as FrameworkElement;
            }
            else if (VisualTreeHelper.GetChildrenCount(control) > 0)
            {
                return VisualTreeHelper.GetChild(control, 0) as FrameworkElement;
            }
        }
 
        return null;
    }
 
    private static Control GetTemplatedParent(FrameworkElement element)
    {
        // If the element has a templated parent, then return that.
        DependencyObject templatedParent = element.TemplatedParent;
        if (templatedParent != null)
        {
            return templatedParent as Control;
        }
 
        // If the element is the root of a UserControl, then it
        // will not have a templated parent. It's Parent property
        // should instead be used.
        UserControl userControl = element.Parent as UserControl;
        if (userControl != null)
        {
            return userControl;
        }
 
        // If the element is the root of a Window, then it
        // will not have a templated parent. It's Parent property
        // should instead be used.
        Window window = element.Parent as Window;
        if (window != null)
        {
            return window;
        }
        // No parent was found.
        return null;
    }

comments