This is a migrated thread and some comments may be shown as answers.

How to use CellStyleSelector in MVVM?

1 Answer 127 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Andrew
Top achievements
Rank 1
Andrew asked on 08 Nov 2012, 01:21 PM
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">
    <GridStyleSelectors:BlockTypeStyleSelector.NormalBlockStyle>
        <Style TargetType="telerik:GridViewCell">
            <Setter Property="Background" Value="White"/>
        </Style>
    </GridStyleSelectors:BlockTypeStyleSelector.NormalBlockStyle>
    <GridStyleSelectors:BlockTypeStyleSelector.CalibrationBlockStyle>
        <Style TargetType="telerik:GridViewCell">
            <Setter Property="Background" Value="PaleGoldenrod"/>
        </Style>
    </GridStyleSelectors:BlockTypeStyleSelector.CalibrationBlockStyle>
</GridStyleSelectors:BlockTypeStyleSelector>

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?

1 Answer, 1 is accepted

Sort by
0
Maya
Telerik team
answered on 08 Nov 2012, 03:42 PM
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). 

Regards,
Maya
the Telerik team

Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Tags
GridView
Asked by
Andrew
Top achievements
Rank 1
Answers by
Maya
Telerik team
Share this question
or