[英]How to set cell color in Vaadin 8 Grid only if row is not selected
[英]How to color a row or cell of a grid depending on it's data in Vaadin 14
假设我有一个Grid<Person>
和一些返回 Enum 的person.getStatus()
enum Status {
SINGLE, MARRIED, DIVORCED
}
我想根据此枚举的值为网格的列着色。
怎么做到呢?
首先,您需要为行设置 CSS 类名生成器。 这会将 CSS 类名添加到 Grid 创建的 td 元素。 生成器函数接收您的项目,如果您不想为某些行添加类名,则应将 CSS 类名作为字符串或 null 返回。 可以从生成器以空格分隔的形式返回多个类名。
grid.setClassNameGenerator(person -> {
if (person.getStatus() == Status.DIVORCED || person.getStatus() == Status.SINGLE) {
return "my-style-1";
} else {
return "my-style-2";
}
});
要根据 CSS 类名更改样式,您需要为 Grid 创建一个主题。
在frontend/styles
文件夹中添加styles.css
。
td.my-style-1 {
background-color: black;
color: hotpink;
}
td.my-style-2 {
background-color: hotpink;
color: black;
}
并将样式包含到您的应用程序中。
@Route
@CssImport(value = "./styles/styles.css", themeFor = "vaadin-grid")
public class MainView extends VerticalLayout {
// your code for grid
}
CSS 样式导入和创建的方式与行样式相同,但使用的 Grid API 不同。
对于单元格,您应该使用列类名称生成器:
grid.getColumnByKey("status").setClassNameGenerator(person -> {
if (person.getStatus() == Status.SINGLE) {
return "my-style-3";
}
return null;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.