Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ScrollIntoView for a DataGrid when using MVVM

0.00/5 (No votes)
8 Nov 2010 1  
I just ran into a small problem with a databound DataGrid in Silverlight. If the SelectedItem is changed by the ViewModel, the DataGrid does not scroll to the SelectedItem.
I created a behavior to do this for me. So now if the Selection of the DataGrid is changed, the DataGrid scolls to the selecteditem. (It used the ScrollIntoView method of the DataGrid.)

C#
namespace MVVM.Framework
{public class ScrollIntoViewBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
        void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is DataGrid)
            {
                DataGrid grid = (sender as DataGrid);
                if (grid.SelectedItem != null)
                {
                    grid.Dispatcher.BeginInvoke(delegate
                    {
                        grid.UpdateLayout();
                        grid.ScrollIntoView(grid.SelectedItem, null);
                    });
                }
            }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.SelectionChanged -=
                new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
    }
}


To use this in XAML: (make sure you have included xmlns:fw="clr-namespace:MVVM.Framework" in your header).

XML
<sdk:DataGrid AutoGenerateColumns="true" ItemsSource="{Binding ObjectList}" SelectedItem="{Binding SelectedObject, Mode=TwoWay}" Name="dataGridObjects">
    <i:Interaction.Behaviors>
        <fw:ScrollIntoViewBehavior/>
    </i:Interaction.Behaviors>
</sdk:DataGrid>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here