Highlight Search String in Silverlight Flexgrid

Many of our users often requested on how to highlight searched text with changed Foreground in Silverlight Flexgrid. This blog explains a simple approach to do this. The implementation involves following steps :

Create a customized Cell Factory class which has a constructor that accepts the text being searched.

Custom CellFactory Class

To create custom cells, you have to create a class that implements the ICellFactory interface and assign this class to the grid's CellFactory property. Like custom columns, custom ICellFactory classes can be highly specialized and application-specific, or they can be general, reusable, configurable classes. In general, custom ICellFactory classes are a lot simpler than custom columns since they deal directly with cells (columns, by contrast, need to deal with the columns themselves and also with the cells and other objects contained in the column).

HightLightCell() Method

The HightLightCell() method is where the Foreground change actually happens. This is done by creating a collection List that consists of the text preceding the text being searched, the actual text being searched and the remaining text. The text appearing before and after the searched text is added to the Inline collection of the TextBlock without any change. The text being searched is also added to the TextBlock's Inline collection, however, with its Foreground changed. Here is the complete code for the Custom Cell Factory

Setting C1Flexgrid.CellFactory

Now, we need to set an instance of this class as the value of C1Flexgrid's CellFactory property. However, here we do it twice. At a button click event and also at KeyDown event of the TextBox that accepts the search string.