Search code examples
uwpcode-behindvisualstatemanagervisualstatesvisualstategroup

UWP - Change Button VisualState dynamically


I am trying to change the button Pressed background dynamically. But I am unable to access to this property from the code behind. According to the base style of button, I tried to get the ControlTemplate (by the TemplateProperty) but there is no method from it to retrieve the Grid (RootGrid) it contains. So I tried to get VisualStateGroup like this:

var visualStateGroups = VisualStateManager.GetVisualStateGroups(testButton);

But this returns null.

Thanks for any help.

Samuel


Solution

  • To retrieve the Grid contained in the Button, you can use the method:

        private TChild FindVisualChild<TChild>(DependencyObject obj)where TChild : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is TChild)
                    return (TChild)child;
                else
                {
                    TChild childOfChild = FindVisualChild<TChild>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
    

    Then use the method like this:

    var grid = FindVisualChild<Grid>(this.test);
    var group = VisualStateManager.GetVisualStateGroups(grid)[0];