简体   繁体   中英

UWP get the vertical offset of Datagrid's ScrollViewer

I'm using a datagrid from "Microsoft.Toolkit.Uwp.UI.Controls" and I'm trying to get the scrollViewer that is built into it to be able to get the vertical offset and implement certain behavior when scrolled all the way to the bottom or the middle. So far I've tried a number of methods I found in other different threads like the one below, that scans the visual tree and gets the scrollViewer. But the value of the verticalOffset property of the scrollViewer returned from this method is always zero and it's events like ViewChanged never gets fired, I've tried calling the updateLayout method but it changed nothing.

I've also tried wrapping the datagrid in a scrollviewer and used that instead. While that worked fine, it caused a huge performance issue due to virtualization. So is there any solution to this?

private ScrollViewer GetScrollViewer(UIElement element)
        {
            if (element == null) return null;

            ScrollViewer retour = null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element) && retour == null; i++)
            {
                if (VisualTreeHelper.GetChild(element, i) is ScrollViewer)
                {
                    retour = (ScrollViewer)(VisualTreeHelper.GetChild(element, i));
                }
                else
                {
                    retour = GetScrollViewer(VisualTreeHelper.GetChild(element, i) as UIElement);
                }
            }
            return retour;
        }

As Oleg Mikhailov mentioned the source code , it was not implemented with ScrollViewer , and we have tested with your code, we can't get the scrollviewer instance. for this scenario, you could detect vertical scrollbar's value change event to get vertical offset, please refer the following code.

var scrollbar = MyFindDataGridChildOfType<ScrollBar>(MyDataGrid);
scrollbar.ValueChanged += Scroll_ValueChanged;
private void Scroll_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
    Debug.WriteLine(e.NewValue);
   // here is vertical value.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM