简体   繁体   English

如何根据 Vaadin 14 中的数据为网格的行或单元格着色

[英]How to color a row or cell of a grid depending on it's data in Vaadin 14

Suppose I have a Grid<Person> and some person.getStatus() which returns an Enum假设我有一个Grid<Person>和一些返回 Enum 的person.getStatus()

enum Status {
SINGLE, MARRIED, DIVORCED
}

I'd like to color the grid's column according to this enum's value.我想根据此枚举的值为网格的列着色。

How can it be done?怎么做到呢?

In Vaadin 14在瓦丁 14

Style a Grid row based on data根据数据设置网格行的样式

First, you need to set the CSS class name generator for the row.首先,您需要为行设置 CSS 类名生成器。 This will add the CSS class name to the td elements created by Grid.这会将 CSS 类名添加到 Grid 创建的 td 元素。 The generator function receives your item and you should return a CSS class name as a String or null if you don't want to add a class name for certain rows.生成器函数接收您的项目,如果您不想为某些行添加类名,则应将 CSS 类名作为字符串或 null 返回。 Multiple class names can be returned from the generator as space-separated.可以从生成器以空格分隔的形式返回多个类名。

grid.setClassNameGenerator(person -> {
    if (person.getStatus() == Status.DIVORCED || person.getStatus() == Status.SINGLE) {
        return "my-style-1";
    } else {
        return "my-style-2";
    }
});

To change the style based on the CSS class names, you need to create a theme for Grid.要根据 CSS 类名更改样式,您需要为 Grid 创建一个主题。

In frontend/styles folder add styles.css .frontend/styles文件夹中添加styles.css

td.my-style-1 {
    background-color: black;
    color: hotpink;
}

td.my-style-2 {
    background-color: hotpink;
    color: black;
}

And include the style to your app.并将样式包含到您的应用程序中。

@Route
@CssImport(value = "./styles/styles.css", themeFor = "vaadin-grid")
public class MainView extends VerticalLayout {
// your code for grid
}

Style a Grid cell based on data根据数据设置网格单元格的样式

The CSS style importing and creating is done the same way as with row styling, but the Grid API used is different. CSS 样式导入和创建的方式与行样式相同,但使用的 Grid API 不同。

For a cell, you should use the column class name generator:对于单元格,您应该使用列类名称生成器:

grid.getColumnByKey("status").setClassNameGenerator(person -> {
    if (person.getStatus() == Status.SINGLE) {
        return "my-style-3";
    }
    return null;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM