Pages

Thursday, November 29, 2012

A behavior to keep DataGrid's SelectedItem into View

The following simple behavior will forces a DataGrid to keep its SelectedItem into view. The way that it works is simply hooking SelectionChanged event and calling DataGrid.ScrollIntoView method.



using System.Windows.Controls;
using System.Windows.Interactivity;
public class KeepSelectionInView : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SelectionChanged += DataGrid_SelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.SelectionChanged -= DataGrid_SelectionChanged;
}
void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (AssociatedObject.SelectedItem != null)
AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItem);
else if (AssociatedObject.SelectedItems != null && AssociatedObject.SelectedItems.Count > 0)
AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItems[0]);
}
}

No comments:

Post a Comment