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
As I'm a bit new to MVVM and data binding, is there a "right" way to do that ?
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...