views:

161

answers:

1

Hi, I'm trying to make a grid that represent bookings over a month(excel style).

For this I have used the WPF Datagrid and defined my column in C# code:

for (int i = 0; i < noOfDaysInMonth; i++)
{
        DataGridTextColumn tmpColumn = new DataGridTextColumn
        {
               Header = (i + 1).ToString(),
               Binding = new Binding("CellStrings[" + i + "]"),
        };

overviewBookingsDataGrid.Columns.Add(tmpColumn); 

Now this works fine. The problem I got is that I don´t know how to style the background color of each cell depending on if the slot is fully booked, partially booked or empty. All examples I have found has been in XAML and defines it togheter with the column and I don't know that translates to C#.

A: 

You need to define a datagridcell style in your XAML. Set some triggers based on the cell's Tag property. For instance if it is "Green" then color your cell green.

Once you have populated your datagrid you can iterate through your table in code, get the datagridcell for each required item, set the cell's tag to a proper value and the style triggers will take care of coloring the cell for you (if you want to clear the background color, set the Tag back to null). Or, if you want to avoid XAML, you can directly set the cells background.

There are plenty of examples on the web how to retrieve a datagridcell for a given item, but I'll give one word of warning - because the wpf datagrid is virtualized by default, you'll need to scroll your items into view and call UpdateLayout() on the item's datagridrow, before you can safely access a datagridcell for a given datagridrow.

Marko