Search code examples
c#asp.netblazorblazor-client-side

How to update classes on binded variable update in Blazor


I have a binded span value on one of my object property

<span class="badge badge-primary">@MyObject?.MyProperty</span>

I want to be able to update my span classes in respect to it's content (the binded variable)

The only way I can think of is to bind the variable a second time inside an attribute of the span and declare my css classes accordingly

<span class="badge badge-primary" value="@MyObject?.MyProperty">@MyObject?.MyProperty</span>
.badge[value="myvalue"]{
    background-color:white;
}

The issue with this approch is that

  • It require me to re-define custom classes for each value when I already have classes in my css framework i could use
  • It can only be applied to a finite list of predefined value
  • I can't use a more comple analysis of my value to descide which class to apply (like checking the value with a regex for exemple)

As I'm a bit new to MVVM and data binding, is there a "right" way to do that ?


Solution

  • You can do that like the following, and you can add as many properties as you want, each representing a different CSS class.

    @page "/"
    
     <span class="badge badge-primary @myObject?.MyProperty">
                                 @myObject?.MyProperty</span>
    
    @code
    {
         MyObject myObject = new MyObject();
    
         public class MyObject
         {
              public string MyProperty { get; set; } = "myvalue";
         }
     }
    

    Hope this helps...

    Update per suggestion:

    <span class="badge @statusColor">@myObject?.MyProperty</span> 
    
    @code{
    
    private string color = "red";
    
    public string statusColor
    {
        get
        {
            if (myObject?.MyProperty == "something")
                color = "blue";
    
            return color;
        }
    }
    
    MyObject myObject = new MyObject();
    
    public class MyObject
    {
        public string MyProperty { get; set; }
    }
    }
    

    I hope this is what you were looking for. My first answer was intended only to demonstrate how you can bind to the span's class attribute, of which you were not aware. As for the rest, you can do whatever you want to achieve your objectives...