ScrollIntoView in Silverlight Datagrid

                Silverlight 2.0 Datagrid ships with a very cool function known as ScrollIntoView. This function provides the functionality to bring into view (show) a particular row or column in the datagrid. I was playing with adding rows to the datagrid, and everytime I add a row, the row gets added to the end of the grid, but the focus is at the top of the Datagrid. In order to see the added row, I have to manually scroll to the bottom of the grid. This function helps to scroll programmatically.

Lets see an example

Page.xaml is defined in this way showing a datagrid and a button

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>

            <RowDefinition Height="400"/>

            <RowDefinition Height="50"/>

        </Grid.RowDefinitions>

        <data:DataGrid x:Name="dg" Grid.Row="0">

           

        </data:DataGrid>

        <Button x:Name="button1" Content="Add" Click="button1_Click" Grid.Row="1"></Button>

    </Grid>

I am using a Customer Class

public class Customer

{

public String FirstName { get; set; }

public String LastName { get; set; }

public int Age { get; set; }

public String Address { get; set; }

public String City { get; set; }

public String Country { get; set; }

}

Initially, the datagrid is populated is populated with 25 customer objects.

            clist = new List<Customer>();

            int count = 25;

            for (int i = 0; i < count; i++)

            {

                Customer cust1 = new Customer("custfname" + i, "custlastname" + i, i, "address" + i, "city" + i, "country" + i);

                clist.Add(cust1);

            }

            dg.ItemsSource = clist;

In the button click event, a new Customer object is added to the list

            int count = clist.Count;

                Customer cust1 = new Customer("custfname" + i, "custlastname" + i, i, "address" + i, "city" + i, "country" + i);

            clist.Add(cust1);

            dg.ItemsSource = null;

            dg.ItemsSource = clist;

 

When the button is clicked, the row is added to the end of the datagrid. We have to manually scroll down to the bottom of list to see the added row.

To scroll to the added row programmatically, we can use the ScrollIntoView function

dg.ScrollIntoView(clist[count], dg.Columns[5]);

The first argument is the row object that should be visible and the 2nd argument specifies the column

 

As you can see, with the scroll into view added to the button click event, we can see the added row and also the column specified is brought into view

Happy DataGrid’ing!