سؤال

I have a GridView. I am using the nested ScrollViewer's SnapPoints to snap each record into view. Because this is only a visual change, and not a data change, how can I determine which record(s) is currently visible? Something like SelectedItem, but a visual query. I could check every record, but it seems inefficient. Ideas?

هل كانت مفيدة؟

المحلول

In your case you could use the VisualTreeHelperExtensions from WinRT XAML Toolkit and do something like this

gridView
    .GetDescendantsOfType<GridViewItem>()
    .Select(gvi => gridView.ItemFromContainer(gvi));

It does a somewhat intensive visual tree search, but might be OK for your scenario if your GridView uses virtualization since the items returned are in or near the view port. If you want to be more precise you can test for bounding rect intersections. Something like this might be enough:

static class RectExtensions
{
    public static bool ContainsPartOf(this Rect bigRect, Rect smallRect)
    {
        // this is a very targeted test for horizontally scrollable smallRects inside of a bigRect
        return bigRect.Left < smallRect.Left && bigRect.Right > smallRect.Left ||
               bigRect.Left < smallRect.Right && bigRect.Right > smallRect.Right;
    }
}

var sv = gridView.GetFirstDescendantOfType<ScrollViewer>();
var bigRect = new Rect(0, 0, sv.ActualWidth, sv.ActualHeight);

gridView
    .GetDescendantsOfType<GridViewItem>()
    .Where(gvi => bigRect.ContainsPartOf(gvi.GetBoundingRect(sv)))
    .Select(gvi => gridView.ItemFromContainer(gvi));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top