DataGrid, reset ScrollViewer to left hand side
Is there a way to reset the Horizontal ScrollViewer of the DataGrid back to all the way on the left? I have it hooked up 开发者_JAVA百科to another control where plots get refreshed. It would be nice if the associated DataGrid gets reset also and has the scrollViewer all the way on the left. Thanks.
You can't access the ScrollViewer
directly, but if you look at the Visual Tree with snoop you can see that is looks like DataGrid
, Border
, ScrollViewer
So to scroll the DataGrid
to the left, you can use the following extension method (or just use a normal method)
public static class DataGridExtensions
{
public static void ScrollToLeft(this DataGrid dataGrid)
{
Border border = VisualTreeHelper.GetChild(dataGrid, 0) as Border;
ScrollViewer scrollViewer = border.Child as ScrollViewer;
scrollViewer.ScrollToLeftEnd();
}
}
Call it like this
dataGrid.ScrollToLeft();
I'm using this to ensure that the first cell of the selected row is visible.
if (dataGrid.SelectedItem != null)
dataGrid.ScrollIntoView(dataGrid.SelectedItem, dataGrid.Columns[0]);
精彩评论