使用MVVM将ScrollIntoView添加到SelectedItem(Windows Phone 8.1)

时间:2015-12-01 14:16:48

标签: xaml listview mvvm windows-phone-8.1

在后面的代码中由

完成
 ActivityList.ScrollIntoView(ActivityList.SelectedItem);

当您从详细信息页面返回时,当您从详细信息页面返回时,您不必从ListView的顶部开始。

有一些示例可以滚动到ListView的末尾,但不能滚动到SelectedItem。

但是如何在MVVM中完成?使用行为SDK创建行为?怎么样?

1 个答案:

答案 0 :(得分:0)

我用附加属性(行为)完成了这项工作。此行为位于名为DataGridExtensions的class中,如下所示:

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;
}