Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Datagrid - Scroll to an item BUT have the item in the middle of the view.

$
0
0

I have a need to have a specific item in the MIDDLE of my datagrid.  The users need to be able to see both items above this item, and items below.  To be even more specific, I'd like the desired item to be always 100 pixels from the top (provided its not one of the first or last items of course).

I have found a way to do this, but I had to set ScrollViewer.CanContentScroll="False".  This severely impacts performance (takes 10 seconds to load the datagrid with 500 items, freezing the program).  This kind of performance isn't acceptable to my end users.

What I did to make it work:  Set ScrollViewer.CanContentScroll="False" such that all the rows were loaded.  Then I got a handle to the DataGridRow that I required to be in the middle (100px down from top), I then determined how many pixels away from the top of the datagrid the item was currently.  I then got a handle to the Datagrid's ScrollViewer, and called Datagrid.ScrollToVerticalOffset(double offset), where offset was a computed value I determined from where the DataGridRow was, and that would put the item in the place I wanted.  Here is the code:

//Method that gets a handle to the scroll viewer of the datagrid
ScrollViewer pScrollViewer = FindVisualChild<ScrollViewer>(pDataGrid); 

//Get a handle to the DataGridRow of the item I want in the middle
DataGridRow pRow = (DataGridRow)pDataGrid.ItemContainerGenerator.ContainerFromItem(pDataGrid.Items[iItemNumber]);

GeneralTransform gt_RowToGrid = pRow.TransformToVisual(pDataGrid);
Point offset_RowToGrid = gt_RowToGrid.Transform(new Point(0, 0)); 

double dScrollToPixels = pScrollViewer.VerticalOffset + offset_RowToGrid.Y - 100;

pScrollViewer.ScrollToVerticalOffset(dScrollToPixels);


Now if I set ScrollViewer.CanContentScroll="True", such that only rows that are visible are loaded, the above solution won't work as the ScrollViewer gets all screwed up.  One idea I had was to force the DataGridRow into view using DataGrid.ScrollIntoView(), then determine where the row is within relation to the top of the datagrid, then I would adjust the scrollviewer up or down 'x' amount of pixels.  Unfortunately there is no way to scroll down say "10 pixels".  There's only a VERY limited number of ways you can adjust the scroll bar.  

Does anyone have a solution for this?  I already know how to put the item at the top or bottom of the view using DataGrid.ScrollIntoView().  I need the item to be in the MIDDLE.  

Thanks in advance.





Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>