Search code examples
xamlxamarinxamarin.formsvisualstatemanager

How to create Resource Style in XAML of VisualStateManager?


Hi I have created an ImagenButton as below:

<ImageButton Source="articulos.png" Clicked="ImageButton_Clicked"/>

And this is the code for animation:

<VisualStateManager.VisualStateGroups>
     <VisualStateGroup x:Name="CommonStates">
          <VisualState x:Name="Normal">
              <VisualState.Setters>
                  <Setter Property="Scale" Value="1"/>
              </VisualState.Setters>
          </VisualState>
          <VisualState x:Name="Pressed">
              <VisualState.Setters>
                  <Setter Property="Scale" Value="0.8"/>
              </VisualState.Setters>
           </VisualState>
       </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

but I want create many buttons with same style, I do not want code repetition.

This is the complete code:

<ImageButton Source="articulos.png" Clicked="ImageButton_Clicked">               
     <VisualStateManager.VisualStateGroups>
          <VisualStateGroup x:Name="CommonStates">
             <VisualState x:Name="Normal">
                 <VisualState.Setters>
                     <Setter Property="Scale" Value="1"/>
                 </VisualState.Setters>
             </VisualState>
             <VisualState x:Name="Pressed">
                 <VisualState.Setters>
                     <Setter Property="Scale" Value="0.8"/>
                 </VisualState.Setters>
              </VisualState>
          </VisualStateGroup>
     </VisualStateManager.VisualStateGroups>
 </ImageButton>

Please help.


Solution

  • You can define styles in your page, and then apply them to your Controls:

    <StackLayout.Resources>
        <Style TargetType="ImageButton">
            <Setter Property="VisualStateManager.VisualStateGroups">
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <VisualState.Setters>
                                    <Setter Property="Scale" Value="1"/>
                                </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="Pressed">
                            <VisualState.Setters>
                                <Setter Property="Scale" Value="0.8"/>
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateGroupList>
            </Setter>
        </Style>
    </StackLayout.Resources
    

    Check the official documentation, it has there an example