Home > Blockchain >  Xamarin switching control's theme
Xamarin switching control's theme

Time:12-10

What i'd like to do is simply change the button's theme using c# when the button is clicked.

What i have in xaml:

BackgroundColor="{x:AppThemeBinding Light={StaticResource Body_Default_Background}, Dark={StaticResource Body_Default_Background_Dark}}"

I want to set the App theme binding using c#

I tried:

button.BackgroundColor = "{x:AppThemeBinding Light={StaticResource Body_Default_Background}, Dark={StaticResource Body_Default_Background_Dark}}"

CodePudding user response:

change the button's theme when the button is clicked

You can simply change the button's BackgroundColor by using VisualStateManager or EventTrigger.

You can refer to the following code:

<Button Text="Click Me!">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="BackgroundColor" Value="Green" />
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="Pressed">
                <VisualState.Setters>
                    <Setter Property="BackgroundColor" Value="Red" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Button>

Or use EventTrigger to achieve this:

create ButtonTriggerAction.cs

public class ButtonTriggerAction : TriggerAction<VisualElement>
{
    public Color BackgroundColor { get; set; }

    protected override void Invoke(VisualElement visual)
    {
        var button = visual as Button;
        if (button == null) return;
        if (BackgroundColor != null) button.BackgroundColor = BackgroundColor;
    }
}

And usage:

<Button Text="using EventTrigger">
    <Button.Triggers>
        <EventTrigger Event="Pressed">
            <local:ButtonTriggerAction BackgroundColor="Red" />
        </EventTrigger>
        <EventTrigger Event="Released">
            <local:ButtonTriggerAction BackgroundColor="Default" />
        </EventTrigger>
    </Button.Triggers>
</Button>
  • Related