Vaadin 10 grid style individual row based on contents

主宰稳场 提交于 2019-12-06 01:20:05

As of now (Vaadin 10, vaadin-grid 5) there is no API for adding custom attributes/classes to individual rows in a grid. It is possible to implement this use case in your application code, but the implementation might be not very efficient.

One approach would be defining a custom renderer for each column of the grid to wrap each cell contents in an extra div, and add classes / attributes to the wrappers. You can use a TemplateRenderer to minimize the memory / performance impact of these wrappers:

Grid<Person> grid = new Grid<>();
grid.setDataProvider(...);

ValueProvider<Person, String> cssClassProvider = (person) -> {
    String cssClass = "my-grid-cell";
    if (person.getAge() <= 16) {
        cssClass += " junior";
    } else if (person.getAge() >= 60) {
        cssClass += " senior";
    }
    return cssClass;
};

grid.addColumn(TemplateRenderer.<Person>
        of("<div class$=\"[[item.class]]\">[[item.age]]</div>")
            .withProperty("class", cssClassProvider)
            .withProperty("age", Person::getAge));
grid.addColumn(TemplateRenderer.<Person>
        of("<div class$=\"[[item.class]]\">[[item.name]]</div>")
            .withProperty("class", cssClassProvider)
            .withProperty("name", Person::getName));

And then you can set the background of the grid cells based on the CSS class (in shared-styles.html):

<custom-style>
  <style>
    .my-grid-cell.junior {
      background-color: coral;
    }

    .my-grid-cell.senior {
      background-color: darkmagenta;
    }
  </style>
</custom-style>

However, that would not look great with the default Lumo theme styles for the Vaadin Grid. In order to make your grid look OK you'll need to override some of these default styles:

<dom-module id="my-grid-theme" theme-for="vaadin-grid">
  <template>
    <style>
      [part~="cell"] {
        min-height: 0;
      }

      [part~="cell"] ::slotted(vaadin-grid-cell-content) {
        padding: 0;
      }
    </style>
  </template>
</dom-module>

<custom-style>
  <style>  
    .my-grid-cell {
      min-height: calc(var(--lumo-size-m) - 2 * var(--lumo-space-xs));
      padding: var(--lumo-space-xs) var(--lumo-space-m);
    }
  </style>
</custom-style>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!