我用附加屬性(行爲)做了這個。此行爲是在class
稱爲DataGridExtensions,看起來像:
public static readonly DependencyProperty ScrollSelectionIntoViewProperty = DependencyProperty.RegisterAttached(
"ScrollSelectionIntoView", typeof(bool), typeof(DataGridExtensions), new PropertyMetadata(false, ScrollSelectionIntoViewChanged));
private static void ScrollSelectionIntoViewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = d as DataGrid;
if (dataGrid == null)
return;
if (e.NewValue is bool && (bool)e.NewValue)
dataGrid.SelectionChanged += DataGridOnSelectionChanged;
else
dataGrid.SelectionChanged -= DataGridOnSelectionChanged;
}
private static void DataGridOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems == null || e.AddedItems.Count == 0)
return;
DataGrid dataGrid = sender as DataGrid;
if (dataGrid == null)
return;
ScrollViewer scrollViewer = UIHelper.FindChildren<ScrollViewer>(dataGrid).FirstOrDefault();
if (scrollViewer != null)
{
dataGrid.ScrollIntoView(e.AddedItems[0]);
}
}
public static void SetScrollSelectionIntoView(DependencyObject element, bool value)
{
element.SetValue(ScrollSelectionIntoViewProperty, value);
}
public static bool GetScrollSelectionIntoView(DependencyObject element)
{
return (bool)element.GetValue(ScrollSelectionIntoViewProperty);
}
的UIHelper.FindChildren
的代碼是:
public static IList<T> FindChildren<T>(DependencyObject element) where T : FrameworkElement
{
List<T> retval = new List<T>();
for (int counter = 0; counter < VisualTreeHelper.GetChildrenCount(element); counter++)
{
FrameworkElement toadd = VisualTreeHelper.GetChild(element, counter) as FrameworkElement;
if (toadd != null)
{
T correctlyTyped = toadd as T;
if (correctlyTyped != null)
{
retval.Add(correctlyTyped);
}
else
{
retval.AddRange(FindChildren<T>(toadd));
}
}
}
return retval;
}