2015-12-01 149 views
1

在這背後的代碼是由ScrollIntoView與MVVM的SelectedItem(的Windows Phone 8.1)

ActivityList.ScrollIntoView(ActivityList.SelectedItem); 

當您從detailpage回來,這樣當你從detailpage回報你不必從開始做ListView的頂部。

有幾個例子可以滾動到一個ListView的結尾,但不是SelectedItem。

但是,在MVVM中這是如何完成的?使用行爲SDK創建行爲?如何?

回答

0

我用附加屬性(行爲)做了這個。此行爲是在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; 
} 
相關問題