I have been using WPF for quiet sometime. I know DataGrid in WPF does not have a Column collection as dependency property so columns cannot be added dynamically.
The application I am developing is highly dynamic so the number of columns are not known. So I am creating DataGridTemplate columns from code behind.
Problem 1 : I want alternating columns to have different background color. How do I do it programatically?? (DataGridTemplateColumn doesnot have a Background property so I am not able to figure out a solution)
Problem 2 : My DataGridTemplateColumn has a DataTemplate in which I have a StackPanel with 2 TextBoxes in it. There is an event in DataGrid called CellEditing Event which fires when we edit a cell. It works for default column, but for my column if I edit those TextBoxes, the event is snot getting fired!!! So how do I achieve it??
(I sometimes get amazed by WPF !!!)
Best Answer
Problem Zero You can have the columns in a datagrid generated for you if you use
AutoGenerateColumns="true"
when you set up your datagrid. It won't add columns dynamically later, but it might if you reset the itemssource? (not positive on that one)Problem One DataGrid has properties
AlternatingRowBackground
andAlternationCount
to set up alternating row backgrounds. But i don't see anything for alternating column backgrounds in the grid itself. You could do it inside your datatemplate, though:But i still see a margin inside that even with margin=0, so the cells look funny if you use any really obvious colors.
Problem Two do you mean the
CellEndEditing
event? Because i don't see any other cell editing events. I tried the following:And my
DataGrid_CellEditEnding
event handler gets called whenever either of the textboxes in the CellEditingTemplate lose focus, whether data changed or not, so things appear to be working for me.Are you using some other DataGrid than the "built in" WPF one?