Search code examples
c#wpfwpfdatagridwpf-stylewpf-grid

Completely remove Grid lines in WPF


I have a WPF Grid with Rectangles in each column. All columns has equal width (1*) and all Rectangles has black background. In designer mode, there are thin lines between the rectangles (the Grid column lines) what is fine, but my problem is, these lines are still visible during run-time:

Example

My code is:

<Grid ShowGridLines="False">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <Rectangle Fill="Black" />
    <Rectangle Grid.Column="1" Fill="Black" />
    <Rectangle Grid.Column="2" Fill="Black" />
    <Rectangle Grid.Column="3" Fill="Black" />
    <Rectangle Grid.Column="4" Fill="Black" />
    <Rectangle Grid.Column="5" Fill="Black" />
</Grid>

Any help would be appreciated!


Solution

  • This issue is because you have a grid with 6 columns, but the width of your grid isn't an exact multiple of 6 pixels. This results in width of each rectangle being a fractional value. For the pixels at the edge of each rectangle, the WPF rendering engine will interpolate between the black rectangle and the window background, giving the grey stripes.

    <Window x:Class="WpfApp2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWi ndow"
            SizeToContent="WidthAndHeight"
            UseLayoutRounding="False">
        <Grid ShowGridLines="False"
              Width="701"
              Height="300">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Rectangle Grid.Column="0"
                       Fill="Black" />
            <Rectangle Grid.Column="1"
                       Fill="Black" />
            <Rectangle Grid.Column="2"
                       Fill="Black" />
            <Rectangle Grid.Column="3"
                       Fill="Black" />
            <Rectangle Grid.Column="4"
                       Fill="Black" />
            <Rectangle Grid.Column="5"
                       Fill="Black" />
        </Grid>
    </Window>
    

    You can see this using a tool such as WPF Snoop

    The fix is either

    • Set the grid width to an exact multiple of 6
    • Set UseLayoutRounding to True

    The latter option will result in some of the rectangles having different widths (by one pixel), but all will be a whole number of pixels.