Search code examples
blazor-server-sideblazorise

Toggle image button (or icon) with blazorise


I'm using Blazorise 0.9.4.7 in a .NET 5 application. I want to have a set of toggle buttons, for example one with Eye and when clicked the Eye transforms into an EyeSlash.

I've tried a couple of alternatives that are not working...Any advice?

<Icon @ref="ShowIcon" Clicked="e => Show(process)" Name="IconName.Eye" />

Then in the cs

public void Show(Process project)
{
    process.ToggleShow();
    ShowProcessIcon.Name = process.Show ? IconName.EyeSlash : IconName.Eye;
}

That's not working on also saying I should not assign anything to Name outside the Icon itself.

I also tried

<Button Clicked="e => Show(process)">
    <ChildContent>
        <Icon Name="IconName.Eye" Visibility="@(process.Show ? Visibility.Visible : 
Visibility.Invisible)"/>
        <Icon Name="IconName.EyeSlash" Visibility="@(process.Show ? Visibility.Invisible : Visibility.Visible)"/>
    </ChildContent>
</Button>

But doesn't work either...

Thanks in advance. Guillermo.


Solution

  • It's better to use one Icon and then just switch the Name based on the visible state.

    <Button Clicked="@ToggleIcon">
        <Icon Name="@(visible ? IconName.Eye : IconName.EyeSlash)" />
    </Button>
    @code {
        bool visible;
    
        Task ToggleIcon()
        {
            visible = !visible;
    
            return Task.CompletedTask;
        }
    }
    

    Also, it is always better to have a Task-able method instead of void. That way Blazor will automatically trigger StateHasChanged for you.