My Master's Thesis Problems and solutions encountered…

11Jul/100

How to add background-color to cells in a DataGrid depending on content

When working on my Silverlight application I found need of giving cells in a DataGrid a specific color, so the user would get a better overview of the shown data. In my application, I have a questionnaire with a list of questions regarding the working and environmental conditions of a company. Now, the answer to each question is beforehand given a color: Red, yellow or green, depending on the severity of answering yes/no to the question.

I wanted to create a Datagrid that gave the creator of the questionnaire an overview over the answers he had created, and the color he given them. I ended up with this:

Step 1: In you .xaml page, create a DataGrid like the one shown below. Notice the Fill="{Binding Converter={StaticResource QuestionsResultConverterYES}}" in the Rectangle.

(Below is only shown the code for the two first columns).

...

xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
...
 <data:DataGrid x:Name="AllQuestionsGrid" MinHeight="10" IsReadOnly="True" Width="350"  AutoGenerateColumns="False" ItemsSource="{Binding QuestionList}" MaxHeight="320" VerticalScrollBarVisibility="Visible" Margin="5 10 5 0" >

    <data:DataGrid.Columns>
        <!--Question Column. -->
        <data:DataGridTemplateColumn Header="Questions" Width="190">
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock TextWrapping="Wrap" Text="{Binding Question}" /> <!-- OT:  This is how you wrap text inside a Datagrid. Simply make TemplateColumn and insert a TextBlock.  -->
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>
        </data:DataGridTemplateColumn>

        <!--Yes-column-->
        <data:DataGridTemplateColumn Header="Yes" Width="auto">
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <Rectangle Margin="4" x:Name="MyRectangle" Fill="{Binding Converter={StaticResource QuestionsResultConverterYES}}" /><!--We will create the Static Resource QuestionsResultConvertYES in the next step -->
                       </Grid>
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>
        </data:DataGridTemplateColumn>

<!-- Repeat for the other no-column-->

    </data:DataGrid.Columns>
</data:DataGrid>

Step 2: Create a new class in your View project. I added a new folder, called Converter, where I put all the Converter classes. In this class we will create a new instance of the object that we want to insert into the datagrid, in my case called QuestionGrid. One of the attributes is called AnswerYes and contains a string with the values "Red", "Yellow" or "Green". So we insert a if-elseif-else that will return a specific SolidColorBrush value depending on the content of the string:


using System.Windows.Data;
using ViewModel.QMServiceReference;

namespace View.Converters
public class QuestionsResultConverterYES : IValueConverter //Important!
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            QuestionGrid ColorYes = value as QuestionGrid;

            if (ColorYes == null)
            {
                return value;
            }
            else if (ColorYes.AnswerYes == "Red")
            {
                return new SolidColorBrush(Color.FromArgb(255, 204, 51, 51)); //red
            }
            else if (ColorYes.AnswerYes == "Yellow")
            {
                return new SolidColorBrush(Color.FromArgb(255, 255, 255, 102)); //yellow
            }
            else if (ColorYes.AnswerYes == "Green")
            {
                return new SolidColorBrush(Color.FromArgb(255, 51, 102, 0));//green
            }
            else
            {
                return new SolidColorBrush(Color.FromArgb(255, 220, 220, 220)); //grey
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Notice that we return a color of the type ARGB. It's basically just normal RGB colors (the last three values), and the first just sets the opacity (255 = 100%, 0 = 0%, that is, transparent).

Step 3: In the App.xaml (where you probably have all your your style deifnitions), you will make the QuestionsResultConverterYES available to your .xaml page.

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:layout="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Layout.Toolkit"
              xmlns:nav="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
             xmlns:converters="clr-namespace:View.Converters" //add
             x:Class="View.App"
             >
        <Application.Resources>
                  <converters:QuestionsResultConverterYES x:Key="QuestionsResultConverterYES"/>
        </Application.Resources>
</Application>

And that's it!

Filed under: Misc. Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment



eight − = 3

No trackbacks yet.