【问题标题】:ScrollIntoView to SelectedItem with MVVM (Windows Phone 8.1)使用 MVVM 将 ScrollIntoView 滚动到 SelectedItem (Windows Phone 8.1)
【发布时间】:2016-03-05 12:06:57
【问题描述】:
后面的代码是由
完成的
ActivityList.ScrollIntoView(ActivityList.SelectedItem);
当您从详细信息页面返回时,当您从详细信息页面返回时,您不必从 ListView 的顶部开始。
有几个示例可以滚动到 ListView 的末尾,但不能滚动到 SelectedItem。
但是这在 MVVM 中是如何完成的呢?使用行为 SDK 创建行为?怎么做?
【问题讨论】:
标签:
xaml
listview
mvvm
windows-phone-8.1
【解决方案1】:
我已经使用附加属性(行为)完成了此操作。此行为在名为 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;
}