WPF/Metro-style: Making ListView show only complete items

前端 未结 3 502
长情又很酷
长情又很酷 2020-12-21 08:29

In my Metro application, I have a data source containing a certain number of items (say 25). I have a ListView that presents those items. My problem is that the ListView hav

3条回答
  •  北海茫月
    2020-12-21 09:34

    The answer from @JesuX is the better approach -- if done correctly. The following ListView subclass works fine for me:

    public sealed class IntegralItemsListView : ListView
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            Size size = base.MeasureOverride(availableSize);
            double height = 0;
            if (Items != null)
            {
                for (int i = 0; i < Items.Count; ++i)
                {
                    UIElement itemContainer = (UIElement)ContainerFromIndex(i);
                    if (itemContainer == null)
                    {
                        break;
                    }
    
                    itemContainer.Measure(availableSize);
                    double childHeight = itemContainer.DesiredSize.Height;
                    if (height + childHeight > size.Height)
                    {
                        break;
                    }
    
                    height += childHeight;
                }
            }
    
            size.Height = height;
            return size;
        }
    }
    

    One caveat -- if you plop an IntegralItemsListView into a Grid, it will have

    VerticalAlignment="Stretch"
    

    by default, which defeats the purpose of this class.

    Also: If the items are of uniform height, the method can obviously be simplified:

    protected override Size MeasureOverride(Size availableSize)
    {
        Size size = base.MeasureOverride(availableSize);
        size.Height = (int)(size.Height / ItemHeight) * ItemHeight;
        return size;
    }
    

提交回复
热议问题