使用图像将ListBox中的Width绑定到ViewportWidth时,水平滚动条可见

时间:2013-04-17 09:36:33

标签: wpf listbox scrollbar border

我想要实现的是在WPF窗口最右侧创建一个带有框架的垂直照片列表。图像是绑定到ObservableCollection的数据,用户可以使用GridSplitter调整图像列表的大小。

目前的代码如下:

    <ListBox Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" ItemsSource="{Binding Sheet.Images}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border Background="#CCC" BorderThickness="8" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollViewer}}, Path=ViewportWidth}">
                    <Image Source="{Binding Contents}"/>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <GridSplitter Grid.Row="0" Grid.Column="1" Grid.RowSpan="3" Width="2" Background="Transparent"/>

它有一个问题 - 无论图像数量多少,水平滚动条始终可见,右边框的一部分被隐藏,除非通过滚动覆盖。 当我绑定到ActualWidth时,问题更加明显,因为滚动条宽度没有从父容器宽度中减去。

如何创建这样一个垂直滚动条的垂直滚动条列表,水平滚动条永远不可见,同时看到整个边框?

还有一个小问题:如何在2个连续图像的边界之间添加距离?

1 个答案:

答案 0 :(得分:1)

我找到了解决这个问题的方法,虽然不是很优雅。 看起来ViewportWidth由于某种原因正好比报告的窄2个像素(或者带图像的边框宽2个像素)。无论如何,我使用了MathConverter,可以找到here

最终结果是:

    <ListBox Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" ItemsSource="{Binding Sheet.Images}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Background="#CCC" BorderThickness="8" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollViewer}},
                        Path=ViewportWidth,
                        Converter={converters:MathConverter},
                        ConverterParameter=@VALUE-2}">
                        <Image Source="{Binding Contents}"/>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
    </ListBox>

    <GridSplitter Grid.Row="0" Grid.Column="1" Grid.RowSpan="3" Width="2" Background="Transparent"/>

如果有人有更好的解决方案,或者至少有理由说明这两个像素导致问题的原因,请随时分享。