Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force zero pixel Gap between Consecutive Cells in WPF DataGrid

i am building an application in WPF for a custom need. First i opted for custom controls, but later on figured out that much of what i needed was already implemented in Datagrid Control. However there is one small glitch:

The problem with Datagrid is that it enforces a minimum of 2 pixel gap between two consecutive cells (1 on each side of the Grid Line). Please have a look at the following diagram for clarity:

. Please note the 2 pixels gap enforced by the Datagrid between the two consecutive cells: http://img265.imageshack.us/img265/3545/figurem.png

(Stack overflow wouldn't let me add image to my question citing a spam protection policy for new users)

.

This doesn't suit my requirement as i want the content to appear "continuous" (There must not be this gap of 2 pixels; i want the connecting lines to look "connected"). i've tried fidgeting with the GridLinesVisibility, but it didn't help. The DataGrid is hosting a custom control like this:

<DataGrid.Columns>
            <DataGridTemplateColumn Width="25" Header="">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ContentControl Content="{Binding Path=MyCustomControl}" Margin="0"></ContentControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

....
</DataGrid.Columns>

i have so far tried:

  1. Switching off the GridLine (see result here: http://img263.imageshack.us/img263/8602/figure2j.png)
  2. Setting the margin of the content property to 0.
  3. Searched google and stackoverflow
  4. Consulted some books.

but nothing seems to come up.

Is there a solution to this/some hack or a workaround or would i have to create everything from scratch? i have decent experience with c#, but i am new to WPF.

Please Help.

like image 563
Bhavneet Singh Bajwa Avatar asked Oct 31 '11 10:10

Bhavneet Singh Bajwa


1 Answers

What you need to do is get at the DataGridCell style for your DataGrid and set its BorderThickness to be 0. It's hard-coded as 1 in the default style, but fortunately it's easy to override this:

<Style TargetType="DataGridCell">
    <Setter Property="BorderThickness" Value="0" />
</Style>

I would suggest putting that into the resources of your DataGrid so it only affects that one grid, unless you want it to have a wider scope than that.

<DataGrid>
    <DataGrid.Resources>
        <Style TargetType="DataGridCell">...</Style>
    </DataGrid.Resources>
    ...
</DataGrid>

There are other places you could put it as well, depending on your precise needs.

like image 66
Matthew Walton Avatar answered Sep 28 '22 05:09

Matthew Walton