尝试根据数据集中的十六进制代码设置单元格背景颜色。没有看到网格本身的属性,所以我尝试通过某种属性绑定将样式绑定到每行的对象Course.ColorHex值。
课程对象
public class Course
{
public int Id { get; set; }
public string CourseTitle { get; set; }
public string CourseDescription { get; set; }
public string ColorHex { get; set; }
}
控制器
[ApiController]
[Route("[controller]")]
public class CourseController : ControllerBase
{
private static readonly string[] colorList = new[] { "#ff0000", "##ffff00", "#00ff00", "#00ffff", "#0000ff", "#ff00ff" };
[HttpGet]
public IEnumerable<Course> GetCourses()
{
var courses = new List<Course>();
for (var i = 0; i < colorList.Length; i++)
{
var idCount = i + 1;
var course = new Course()
{
Id = idCount,
CourseTitle = $"Course {idCount}",
CourseDescription = $"Course {idCount} description",
ColorHex = colorList[i]
};
courses.Add(course);
}
var result = courses.ToArray();
return result;
}
}
Blazor
@page "/grid"
@using TelerikGridColorTest.Shared
@inject HttpClient Http
<h3>Courses</h3>
<TelerikGrid Data="courses">
<GridColumns>
<GridColumn Field="@(nameof(Course.CourseTitle))" />
<GridColumn Field="@(nameof(Course.CourseDescription))" />
<GridColumn>
<Template>
<div style="background-color: @(nameof(Course.ColorHex)); padding: 10px;"></div>
</Template>
</GridColumn>
</GridColumns>
</TelerikGrid>
@code {
Course[] courses { get; set; }
protected override async Task OnInitializedAsync()
{
courses = await Http.GetFromJsonAsync<Course[]>("Course");
}
}
想明白了。忘记了我在field属性中使用的字段的一个地址。
@page "/grid"
@using TelerikGridColorTest.Shared
@inject HttpClient Http
<h3>Courses</h3>
<TelerikGrid Data="courses">
<GridColumns>
<GridColumn Field="@(nameof(Course.CourseTitle))" />
<GridColumn Field="@(nameof(Course.CourseDescription))" />
<GridColumn Field="@(nameof(Course.ColorHex))">
<Template>
@{
var color = context as Course;
<div style="background-color: @(color.ColorHex); padding: 10px;"></div>
}
</Template>
</GridColumn>
</GridColumns>
</TelerikGrid>
@code {
Course[] courses { get; set; }
protected override async Task OnInitializedAsync()
{
courses = await Http.GetFromJsonAsync<Course[]>("Course");
}
}