Prevent WPF ListView or ListBox from showing “half” Items

笑着哭i 提交于 2019-12-04 07:40:32

There's no way I know of to fix a ListView this way. For ListBox, though, you can override ArrangeOverride and arrange the items yourself. Stack the items you want to see, and arrange the items you do not wish to be visible (e.g., partially visible items) so that they are not visible. For example, a non-virtualized version:

    /// <summary>
    /// Used to arrange all of the child items for the layout.
    /// Determines position for each child.
    /// </summary>
    /// <param name="finalSize">Parent passes this size in</param>
    /// <returns>Parent size (always uses all of the allowed area)</returns>
    protected override Size ArrangeOverride(Size finalSize)
    {
        // Arrange in a stack
        double curX = 0;
        double curY = 0;
        foreach (UIElement child in InternalChildren)
        {
            double nextY = curY + child.DesiredSize.Height;
            if (nextY > finalSize.Height)         // Don't display partial items
                child.Arrange(new Rect());
            else
                child.Arrange(new Rect(curX, curY, child.DesiredSize.Width, child.DesiredSize.Height);
            curY = nextY;
        }

        return finalSize;
    }

You just have to set MinHeight or MinWidth to the cell which you'r resizing. Try this:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition MinHeight="50"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition MinHeight="50"/>
        </Grid.RowDefinitions>
        <ListBox HorizontalAlignment="Center" Margin="10">
            <ListBoxItem>First</ListBoxItem>
            <ListBoxItem>Second</ListBoxItem>
            <ListBoxItem>Third</ListBoxItem>
            <ListBoxItem>Fourth</ListBoxItem>
        </ListBox>
        <GridSplitter Grid.Row="1" Height="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        <ListView Grid.Row="2" Margin="4">
            <ListViewItem>First</ListViewItem>
            <ListViewItem>Second</ListViewItem>
            <ListViewItem>Third</ListViewItem>
            <ListViewItem>Fourth</ListViewItem>
        </ListView>
    </Grid>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!