HelpBot Assistant

How can I help you?

Visual States in Xamarin Button (SfButton)

10 Jul 20233 minutes to read

The button visual can be customized through VisualStates. The SfButton control have the following four visual states:

  • Normal
  • Pressed
  • Checked
  • Unchecked
  • Disabled

NOTE

  • In addition, MouseOver VisualState is available only in the UWP platform.
  • The visual states Checked and Unchecked are only updated when enabling the IsChecked property in SfButton.
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <buttons:SfButton x:Name="SfButton" WidthRequest="100" Text="Button">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <VisualState.Setters>
                        <Setter Property="TextColor" Value="White" />
                    </VisualState.Setters>
                </VisualState>

                <VisualState x:Name="Pressed">
                    <VisualState.Setters>
                        <Setter Property="TextColor" Value="Black" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </buttons:SfButton>
</StackLayout>
StackLayout stackLayout = new StackLayout
{
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center
};
SfButton button = new SfButton
{
    Text = "Button",
    WidthRequest = 100
};

VisualStateGroupList visualStateGroupList = new VisualStateGroupList();

VisualStateGroup commonStateGroup = new VisualStateGroup();
VisualState normalState = new VisualState
{
    Name = "Normal"
};
normalState.Setters.Add(new Setter { Property = SfButton.TextColorProperty, Value = Color.White });

VisualState pressedState = new VisualState
{
    Name = "Pressed"
};
pressedState.Setters.Add(new Setter { Property = SfButton.TextColorProperty, Value = Color.Black });

commonStateGroup.States.Add(normalState);
commonStateGroup.States.Add(pressedState);
visualStateGroupList.Add(commonStateGroup);

VisualStateManager.SetVisualStateGroups(button, visualStateGroupList);

stackLayout.Children.Add(button);
this.Content = stackLayout;

Pressed visual state:
SfButton with visual state

Normal visual state:
SfButton with visual state

See also

How to change Xamarin.Forms button style using its visual states