How to use CellStyleSelector in MVVM?

2 posts, 0 answers
  1. Andrew
    Andrew avatar
    8 posts
    Member since:
    Nov 2012

    Posted 08 Nov 2012 Link to this post

    I've followed your help sample and created a custom style selector like this:-

    public class BlockTypeStyleSelector : StyleSelector
        public override Style SelectStyle(object item, DependencyObject container)
            if (item is SampleRun)
                var sampleRun = item as SampleRun;
                switch (sampleRun.BlockType)
                    case BlockType.NormalBlock:
                        return NormalBlockStyle;
                    case BlockType.CalibrationBlock:
                        return CalibrationBlockStyle;
            return null;
        public Style NormalBlockStyle { get; set; }
        public Style CalibrationBlockStyle { get; set; }

    I have also created the necessary styles in my view XAML:-

    <GridStyleSelectors:BlockTypeStyleSelector x:Key="blockTypeStyle">
            <Style TargetType="telerik:GridViewCell">
                <Setter Property="Background" Value="White"/>
            <Style TargetType="telerik:GridViewCell">
                <Setter Property="Background" Value="PaleGoldenrod"/>

    The problem is, I'm programmatically creating the RadGridView columns in my view model. I can't simply assign an instance of my custom style selector to the column's CellStyleSelector property as there is nothing linking that instance to the styles in the XAML. Am I going about this the wrong way?

  2. Maya
    Maya avatar
    4062 posts

    Posted 08 Nov 2012 Link to this post

    Hello Andrew,

    It is not recommended to create any visual elements and assign any properties to them in your ViewModel. It totally breaks the whole idea behind Model-View-ViewModel pattern. What I would suggest is to keep your ViewModel strictly for the data and use is as a link between your business objects and views. Thus you will be able to assign easily the style selector to the column you want (either in xaml or in code-behind). 

    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Back to Top