Scrolling data into View in a WPF Datagrid

There may be cases where you’d want to programmatically select an item in a WPF datagrid or a list. Usually, if the collection is large and only a part of it is visible at a time, you would also want the items to scroll into view automatically. Otherwise there’s no point in “selecting” an item if it’s hidden from view.

Let’s take, as an example, an instance where you have a DataGrid and you already have logic in place for programmatically selecting an item.
Now you simply need to create a handler for SelectionChanged event of the DataGrid:

....
<DataGrid SelectionChanged="DataGrid_SelectionChanged">
....
....

And the handler goes something like this:

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var myDataGrid = sender as DataGrid;
    myDataGrid.ScrollIntoView(myDataGrid.SelectedItem);
}

This also takes care of cases where an item in the view is partially cut off, for example when it is at the top or the bottom of the viewer. When the user clicks on the partially hidden item, the handler again kicks in and moves it just a little so it is completely visible. Probably a nice functionality to have in user friendly UIs.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>