Monday, July 14, 2014

Paint WPF DataGridCell background w/o using IValueConverter

Here's how to paint WPF DatagridCell using extension methods without using IValueConverter.
Extension Method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Module DataGridExtensions
    <Extension()>
    Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
        Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        If row Is Nothing Then
            grid.UpdateLayout()
            grid.ScrollIntoView(grid.Items(index))
            row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        End If
        Return row
    End Function
End Module

MainWindow.xaml:
1
2
3
4
Dim firstRow As DataGridRow = grid1.GetRow(0) 'grid1 is your DataGrid control
Dim firstColumnInFirstRow As Controls.DataGridCell = DirectCast(grid1.Columns(0).GetCellContent(firstRow).Parent, Controls.DataGridCell)
'set background
firstColumnInFirstRow.Background = Brushes.Red

0 comments:

Post a Comment