Created
December 15, 2010 16:32
-
-
Save kekonn/742208 to your computer and use it in GitHub Desktop.
For a tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Controls.Primitives; | |
using System.Windows.Media; | |
namespace InfiniteScroll | |
{ | |
public class InfiniteScrollingListBox : ListBox | |
{ | |
public static readonly DependencyProperty EarlyLoadingFactorProperty = | |
DependencyProperty.Register("EarlyLoadingFactor", typeof (float), typeof (InfiniteScrollingListBox), | |
new PropertyMetadata(0.1f)); | |
public static readonly DependencyProperty EagernessProperty = DependencyProperty.Register("Eagerness", | |
typeof (int), | |
typeof ( | |
InfiniteScrollingListBox | |
), | |
new PropertyMetadata( | |
10)); | |
private bool bound = false; | |
public float EarlyLoadingFactor | |
{ | |
get { return (float) GetValue(EarlyLoadingFactorProperty); } | |
set { SetValue(EarlyLoadingFactorProperty,value);} | |
} | |
public int Eagerness | |
{ | |
get { return (int) GetValue(EagernessProperty); } | |
set { SetValue(EagernessProperty,value);} | |
} | |
public InfiniteScrollingListBox() : base() | |
{ | |
LayoutUpdated += InfiniteScrollingListBoxLayoutUpdated; // We can't initialize here, there's no layout yet | |
} | |
void InfiniteScrollingListBoxLayoutUpdated(object source, EventArgs e) | |
{ | |
if (bound) return; | |
// find the scrollviewer | |
ScrollViewer scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer; | |
if (scrollViewer == null) throw new Exception("No ScrollViewer found"); | |
// find the scrollviewer's scrollbar | |
ScrollBar scrollBar = | |
((FrameworkElement)VisualTreeHelper.GetChild(scrollViewer, 0)).FindName("VerticalScrollBar") as | |
ScrollBar; | |
if (scrollBar == null) throw new Exception("Could not find scrollbar"); | |
//register event handler | |
scrollBar.ValueChanged += (sender, args) => | |
{ | |
Debug.WriteLine(args.NewValue); | |
if (scrollBar.Maximum - (scrollBar.Maximum * EarlyLoadingFactor) >= args.NewValue) return; | |
IInfiniteScrollingItemsSource src = | |
ItemsSource as IInfiniteScrollingItemsSource; | |
if (src == null) return; | |
src.GetMoreItems(Eagerness); // if we need to do some loading and we have the right itemssource, do so | |
}; | |
bound = true; | |
} | |
public void LoadItems() | |
{ | |
IInfiniteScrollingItemsSource src = ItemsSource as IInfiniteScrollingItemsSource; | |
if (src == null) return; | |
src.GetMoreItems(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment