滚动时 ListBox 内部的 ContentControl 会超出 ListBox

ContentControl inside ListBox going outside ListBox when scrolled

我目前有一个 ListBox,它有一个 DataTemplate(对于自定义 class),它是一个 TabControl(绑定到图表列表),其中包含a ContentControl(显示图表)。

当我滚动 ListBox 时,TabControl 的选项卡正确地离开屏幕。但是,TabControl 中的 ContentControl 图表超出了 ListBox 并覆盖了其他元素。

代码示例:

<ListBox x:Name="ListBox" ItemsSource="{Binding ChartItemsList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListBox.Resources>
    <DataTemplate DataType="{x:Type m:ChartItemsWrapper}">
        <StackPanel Orientation="Horizontal">
            <shared:PixelSnapper>
                <TabControl Background="White" BorderBrush="DarkGray" ItemsSource="{Binding Items}" Margin="3,0" Padding="0" TabStripPlacement="Right">
                    <TabControl.ContentTemplate>
                        <DataTemplate>
                            <DockPanel LastChildFill="True">
                                <Border BorderBrush="DarkGray" BorderThickness="0,1,0,0">
                                    <Grid Background="White">
                                        <Stuff>
                                        <Grid Margin="0,25,0,0">
                                            <ContentControl Content="{Binding Chart}" Visibility="Collapsed" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" x:Name="mainChart"/>
                                        </Grid>
                                    </Grid>
                                </Border>
                            </DockPanel>
                        <DataTemplate.Triggers ... />
                        </DataTemplate>
                    </TabControl.ContentTemplate>
                    <TabControl.ItemTemplate ... />
                    <TabControl.ItemContainerStyle ... />
                </TabControl>
            </shared:PixelSnapper>
        </StackPanel>
    </DataTemplate>
</ListBox.Resources>
<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <WrapPanel FlowDirection="LeftToRight" IsItemsHost="True"  Orientation="Horizontal"></WrapPanel>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

我尝试设置 ZIndexes,更改绑定,但似乎 ListBoxes 和 ContentControls 不混合。任何帮助将不胜感激。

HorizontalContentAlignment="Stretch" 添加到您的列表框。 我之前遇到过类似的问题,这解决了我的问题。

除了 vishakh369 建议的 HorizontalContentAlignment="Stretch",您还可以尝试 ClipToBounds="True"。虽然不确定有什么区别,也许您可​​以尝试一下,看看哪个更好。

抱歉,这不会成为大多数人将来会发现有用的答案,但在我的特定情况下,<ContentControl Content="{Binding Chart}" .../> 的绑定指向只能在 WinFormHost 中显示的图表。

由于 WinForms 和 WPF 是不同的呈现技术,并且 WinForms UI 元素将始终覆盖在 WPF 元素之上,这导致我的 WinForm 图表在应该滚动时超出了列表框 "off screen."

有关这方面的更多信息,请参阅 this Whosebug question or this MSDN post. A note, in my research, some people were saying this problem was fixed in the .NET 4.5 release but it seems that it was not due to complications and had to be dropped from the release (see link)。