Search code examples
wpflistviewuser-controlsdpi

Incorrect pixel size for same height in ListView: how to enforce pixel height/size


I have a ListView that hosts multiple instances of an user control in a C# WPF application.

This user control displays a horizontal line that always has the same size "1".

However on screen, the lines that should have the same height display with +/-1 pixel height difference!!!

First line is thicker

First two lines are thinner!!!

Question: How can I enforce that rendering will render the lines with the same PIXEL height?!

Here the Line definition in the user control:

Line definition of the user control:

<Rectangle Grid.Row         = "1"
           Grid.Column      = "0"
           Grid.ColumnSpan  = "2"
           Fill             = "DodgerBlue"
           Height           = "1"
           Margin           = "0, 1, 0, 2" />

and the ListView:

<ListView ItemsSource                   = "{Binding FoundBooks, Mode=OneWay}"
          SelectedItem                  = "{Binding SelectedBookPreview}"
          Grid.Row                      = "1" 
          Grid.Column                   = "0" 
          SelectionMode                 = "Single"
          HorizontalContentAlignment    = "Stretch">

    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type vm:vmLessonBookPreview}">
            <ucont:ucLessonBookListViewItem DataContext         = "{Binding}"
                                            HorizontalAlignment = "Stretch" 
                                            Margin              = "-3, 0, -3, 0" />
        </DataTemplate>
    </ListView.ItemTemplate>

</ListView>

More notes;

  • The line-height does only depend on the display position in the control, not on the index number (so first line will always have same size different than 2nd line for example, even when I scroll)
  • Tested with ListView, ItemsControl and ComboBox, all the same issues
  • Controls added manually in a ScrollViewer do not behave like this
  • Using px sizes (e.g. Height = "2px" does not change anything!)

It really seems to be an issue with the ItemsControl presenter, could it be a bug?


Solution

  • OK, the solution was really simple although finding it was more luck than anything else...

    I just had to add UseLayoutRounding to the Rectangle control...:

    <Rectangle Grid.Row             = "1"
               Grid.Column          = "0"
               Grid.ColumnSpan      = "2"
               Fill                 = "DodgerBlue"
               UseLayoutRounding    = "True" 
               Height               = "1"
               Margin               = "0, 1, 0, 2" />
    

    I hope it will help others too!