Search code examples
c#asp.net-coreblazorblazor-server-sideasp.net-blazor

Is there a shorter way of accomplishing this task in Blazor?


<div class="container">
    @foreach (var item in todos)
    {
    <div class="row">
        <div class="col-sm-6">
            <input type="checkbox" @bind="item.IsDone"/>
            @if(item.IsDone){
                <span style="text-decoration: line-through">@item.Title</span>
            }else{
                <span>@item.Title</span>
            }
        </div>
    </div>
    }
</div>

<input placeholder="Something todo" @bind="newTodo"/>
<button @onclick="AddTodo">Add todo</button>

I want the style to apply when an item is checked, but in a more concise way using only data binding without the 'if' statement.


Solution

  • You can do something like this...

    In your ToDo class definition add a new field named

     public string Style => IsDone ? "text-decoration: line-through" : ""; 
    

    And the usage would be:

    <input type="checkbox" @bind="item.IsDone"/>
    <span style="@item.Style">@item.Title</span>
    

    Hope this helps...