Demodave
Demodave

Reputation: 6632

How to detect if a ListView in WPF would need scrolling?

I have several items in a list view in WPF. I'm wanting to add some items to the next "page" when they reach beyond the viewing area. However, I don't want scrolling available. I disable the scrolling.

<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled">

I don't want scrolling at all, I only want to know if there are items beyond the scrolling. Currently I limit the list by number of items on the page, however my items are not same size nor would I know the size of the screen so this needs to be adjustable.

Upvotes: 0

Views: 419

Answers (1)

Demodave
Demodave

Reputation: 6632

Although this is a solution and works, it doesn't appear to be good on performance need another answer.

In order to speed up performance I now tempNumItemsPerPage = tempNumItemsPerPage -2;

1) Added an Event handler for the scrollchange in the constructor

public ViewName()
{
    InitializeComponent();

    // Handler to add scroll change event
    Items.AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(Items_ScrollChanged));

    Init();            
}

2) Added the Event onto my listview

<ListView ScrollViewer.ScrollChanged="OrderItems_ScrollChanged">

3) Add the scrollchanged code

private void OrderItems_ScrollChanged(object sender, ScrollChangedEventArgs scrollChangedEventArgs)
{
    ScrollViewer scrollViewer = Extensions.WPFExtensions.GetChildOfType<ScrollViewer>(Items);

    if (scrollViewer.ComputedHorizontalScrollBarVisibility == Visibility.Visible)
    {
        GetItemsOnPage();

        tempNumItemsPerPage--;               
    }
}

The only issue I have is it resets the page everytime seeing if the scrollbar is off [not visible to the eye].

public static class WPFExtensions
{
    public static T GetChildOfType<T>(this DependencyObject depObj)
        where T : DependencyObject
    {
        if (depObj == null) return null;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);

            var result = (child as T) ?? GetChildOfType<T>(child);
            if (result != null) return result;
        }

        return null;

    }
}

Upvotes: 0

Related Questions