Skip to main content Skip to footer

Using a Custom CellFactory in MVVM Scenarios

The scenario is simple: a user wants to customize the way the FlexGrid displays information based on its state. For instance, when a row is collapsed it should display as one style, and when it’s expanded it should display as another style. How can you achieve this type of logic in the XAML world while still obeying the laws of MVVM? The answer is very simple: use a Cell Factory. Cell factories are similar to value converters but they are special to the C1FlexGrid control. They can be written in C#/VB while still being referenced in XAML as a resource in your application. So if you are an MVVM workshop then you can use the CellFactory interface in the same way you use converters. Why use a CellFactory over a converter? Converters are very generic, and also somewhat limited. In our example mentioned above a converter would have to figure out whether the row is expanded or collapsed, and that information is external to the converter. Then you get into the issue of passing the FlexGrid control as a parameter to the converter. Ugh! You can bypass this altogether with a cell factory because it has access to pretty much every aspect of the grid. So if you find yourself needing to dynamically alter the way FlexGrid displays or behaves on a cell-basis – look into using a CellFactory instead of writing a converter. Then declare it as a Resource and use it in XAML as you would with any regular Converter (if you so choose). Below are some code snippets and attached is a complete sample which shows how to alter a cell based upon its collapsed state.

   <local:MyCellFactory x:Key="_myfactory" />  
    CellFactory="{StaticResource _myfactory}" />  

public class MyCellFactory : C1.Silverlight.FlexGrid.CellFactory  
    public override FrameworkElement CreateCell(C1.Silverlight.FlexGrid.C1FlexGrid grid, C1.Silverlight.FlexGrid.CellType cellType, C1.Silverlight.FlexGrid.CellRange range)  
        var cell = base.CreateCell(grid, cellType, range) as Border;  
        if (cellType == C1.Silverlight.FlexGrid.CellType.Cell &amp;amp;&amp;amp; range.Column == 0)  
            var gr = grid.Rows[range.Row] as C1.Silverlight.FlexGrid.GroupRow;  
            if (gr != null &amp;amp;&amp;amp; gr.HasChildren &amp;amp;&amp;amp; !gr.IsCollapsed)  
                foreach (var tb in C1.Util.Util.GetChildrenOfType&amp;lt;TextBlock&amp;gt;(cell))  
                    tb.Opacity = 0;  
        return cell;  

Download Sample

ComponentOne Product Manager Greg Lutz

Greg Lutz

comments powered by Disqus