Telerik blogs

I’m happy to announce that with our upcoming Q1 2010 Service Pack 1 (middle of April) you will be able to apply conditionally styles and templates for RadGridView easily using DataTemplateSelectors and StyleSelectors for both Silverlight and WPF:

image

You can test the new functionally with our upcoming latest internal build this Friday and in the meantime here is an example:

XAML

<Grid x:Name="LayoutRoot">
<
Grid.Resources>
<
local:MyStyleSelector x:Key="styleSelector" />
<
local:MyDataTemplateSelector x:Key="templateSelector" />
</
Grid.Resources>
<
telerik:RadGridView AutoGenerateColumns="False" ItemsSource="{Binding}" RowStyleSelector="{StaticResource styleSelector}">
<
telerik:RadGridView.Columns>
<
telerik:GridViewDataColumn DataMemberBinding="{Binding ID}" CellTemplateSelector="{StaticResource templateSelector}" />
</
telerik:RadGridView.Columns>
</
telerik:RadGridView>
</
Grid>
 
 

C#

public class MyStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
var style = style = new Style(typeof(GridViewRow));

var row = (GridViewRow)container;
var obj = (MyObject)item;

if (obj.ID > 50)
{
style.Setters.Add(new Setter(GridViewRow.BackgroundProperty, new SolidColorBrush(Colors.Red)));
}
else
{
style.Setters.Add(new Setter(GridViewRow.BackgroundProperty, new SolidColorBrush(Colors.Blue)));

}

return style;
}
}

public class MyDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var template = base.SelectTemplate(item, container);

var cell = (GridViewCell)container;
var obj = (MyObject)item;

if (obj.ID > 50)
{
template = (DataTemplate)XamlReader.Load(
@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
<TextBlock Text=""{Binding ID}"" />
</DataTemplate>"
);
}
else
{
template = (DataTemplate)XamlReader.Load(
@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
<TextBox Text=""{Binding ID}"" />
</DataTemplate>"
);
}

return template;
}
}
New properties are:

GridViewColumn
- CellTemplateSelector
- CellEditTemplateSelector
- ToolTipTemplateSelector
- GroupHeaderTemplateSelector
- GroupFooterTemplateSelector
- CellStyleSelector
- GroupFooterCellStyleSelector

GridViewDataControl
- RowDetailsTemplateSelector
- HierachyChildTemplateSelector
- RowStyleSelector
- AlternateRowStyleSelector
- GroupRowStyleSelector
- GroupFooterRowStyleSelector
- RowDetailsStyleSelector

Important: If you set respective Style or DataTemplate property (for example CellStyle/CellStyleSelector) the Style/DataTemplate selector will not be applied!

Enjoy!


About the Author

Vladimir Enchev

is Director of Engineering, Native Mobile UI & Frameworks

Comments

Comments are disabled in preview mode.