Question

I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight.

Was it helpful?

Solution

This is slightly old code (from before RTM), but does something like what you're looking for. It checks some data on an object in a row and then sets the colour of the row accordingly.

XAML:

<my:DataGrid x:Name="Grid" Grid.Row="1" Margin="5" GridlinesVisibility="None" PreparingRow="Grid_PreparingRow">
    <my:DataGrid.Columns>
        <my:DataGridTextBoxColumn 
            DisplayMemberBinding="{Binding Cheese}" 
            Header="Cheese"></my:DataGridTextBoxColumn>
        <my:DataGridTextBoxColumn 
            DisplayMemberBinding="{Binding Biscuit}" 
            Header="Biscuit"></my:DataGridTextBoxColumn>
    </my:DataGrid.Columns>
</my:DataGrid>

Code:

this.Grid.AlternatingRowBackground = null; 

private void Grid_PreparingRow(object sender, DataGridRowEventArgs e)
{
    CheesyClass c = e.Row.DataContext as CheesyClass;
    if (c != null && c.Cheese == "cheddar")
    {
       e.Row.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 125, 125));
    }
}

OTHER TIPS

Actually this won't work in all examples. See these links for the 'proper' way of achieving this

http://silverlight.net/forums/p/27465/93474.aspx#93474

http://silverlight.net/forums/t/27467.aspx

I've generally written custom ValueConverters for each data type being bound that return Visibility, Colour, etc.

This gives a single point where the customisation rules are defined and I've found works very well.

Robin's second link describes writing a custom ValueConverter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top