Search code examples
c#wpflistboxsnapstodevicepixels

WPF Listbox border on right side blurry


I have a WPF application with a listbox showing some data. When i have the listbox in the center of the window and the window is an uneven width, on the right side the listbox is blurry. (Green is Rectangle, the blue part is a textbox) the (green) listbox has a blurry right side I tried to apply SnapsToDevicePixels virtually everywhere without result. (I know it should be inherited by child elements, but im almost pulling my hairs out)

I could overcome this by having it set to HorizontalAlignment="Left" and have is always at a fixed size, but i know i'm just missing something, as the textbox does get rendered correct.

Here is my (as clean as possible)code, showing the behavior:

<Window x:Class="WpfApplication2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"  
    Height="200" 
    Width="401px"  
    Background="Red" 
    SnapsToDevicePixels="True">
<Grid>
    <Rectangle Width="200" Height="50"  Fill="Blue" VerticalAlignment="Top" />
    <ListBox Height="94" VerticalAlignment="Bottom"  Width="200px" >
        <ListBoxItem>1</ListBoxItem>
        <ListBox.Template>
            <ControlTemplate TargetType="ListBox">
                <ScrollViewer Margin="0" Padding="0" SnapsToDevicePixels="True">
                    <StackPanel Margin="0" IsItemsHost="True" Width="200" Background="GreenYellow"/>
                </ScrollViewer>
            </ControlTemplate>
        </ListBox.Template>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="SnapsToDevicePixels" Value="True"/>
                <Setter Property="Width" Value="200"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Grid Background="Green" Height="40" SnapsToDevicePixels="True">
                                <ContentPresenter SnapsToDevicePixels="True"/>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</Grid>
</Window>

Solution

  • Set UseLayoutRounding="True" on the Window.

    I also recommend setting TextOptions.TextFormattingMode="Display" to improve text clarity.