Binding Background (color) for the entire row of a telerik:GridViewDataControl WPF control

Stephen Swensen picture Stephen Swensen · Sep 10, 2010 · Viewed 10.7k times · Source

I have the following class:

public class ErrorMessage
{
    public enum Severity { Error, Warning}

    public ErrorMessage(Severity severity, string description) 
    {
        this.severity = severity;
        this.description = description;
    }
    public Severity severity { get; set; }
    public string description { get; set; }
    public string background
    {
        get
        {
            switch (this.severity)
            {
                case Severity.Error: return "Red";
                case Severity.Warning: return "Yellow";
                default: throw new Exception("severity out of bounds");
            }
        }
    }
}

And I am binding a List of ErrorMessage to a telerik GridViewDataControl WPF control:

<telerik:GridViewDataControl Margin="0" telerik:StyleManager.Theme="Office_Silver" Name="errorsGridView" AutoGenerateColumns="False" CanUserSortColumns="False" IsFilteringAllowed="False" ShowGroupPanel="False">
    <telerik:GridViewDataControl.Columns>
        <telerik:GridViewDataColumn IsReadOnly="True" UniqueName="{x:Null}" Header="Severity" DataMemberBinding="{Binding severity}" />
        <telerik:GridViewDataColumn IsReadOnly="True" UniqueName="{x:Null}" Header="Description" DataMemberBinding="{Binding description}" />
    </telerik:GridViewDataControl.Columns>
</telerik:GridViewDataControl>

I would like the entire Background color of each row to be bound to by the ErrorMessage.background property. How do I do this? Thanks in advance!

Answer

Evan Hutnick picture Evan Hutnick · Sep 10, 2010

Another method is to use a RowStyle that has binding from your class. To avoid having to use any converter or even an event, change your ErrorMessage code to something like this:

public SolidColorBrush background
{
    get
    {        
        switch (this.severity)
        {
            case Severity.Error: return new SolidColorBrush(Colors.Red);                   
            case Severity.Warning: return new SolidColorBrush(Colors.Yellow);
            default: throw new Exception("severity out of bounds");
        }
    }
}

And then add this resource:

        <Style x:Key="xGridViewRowStyle"
               TargetType="telerik:GridViewRow">
            <Setter Property="Background"
                    Value="{Binding background}" />
        </Style>

And on RadGridView:

RowStyle="{StaticResource xGridViewRowStyle}"

Slightly different approach, but just tested it and it definitely works. :)