恕我直言,最清晰的方法是通过AttachedProperty 使用“行为”。 AttachedProperty 是一种扩展现有控件功能的机制。
首先,创建一个类来保存AtachedProperty,例如:
public class ScrollViewerBehavior
{
public static bool GetAutoScrollToTop(DependencyObject obj)
{
return (bool)obj.GetValue(AutoScrollToTopProperty);
}
public static void SetAutoScrollToTop(DependencyObject obj, bool value)
{
obj.SetValue(AutoScrollToTopProperty, value);
}
public static readonly DependencyProperty AutoScrollToTopProperty =
DependencyProperty.RegisterAttached("AutoScrollToTop", typeof(bool), typeof(ScrollViewerBehavior), new PropertyMetadata(false, (o, e) =>
{
var scrollViewer = o as ScrollViewer;
if (scrollViewer == null)
{
return;
}
if ((bool)e.NewValue)
{
scrollViewer.ScrollToTop();
SetAutoScrollToTop(o, false);
}
}));
}
此附加属性允许ScrollViewer“神奇地”拥有Boolean 类型的新属性,就像您的XAML 中的DependencyProperty。如果将此属性绑定到 ViewModel 中的标准属性,例如:
private bool _reset;
public bool Reset
{
get { return _reset; }
set
{
_reset = value;
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Reset"));
}
}
(同样,名称由您决定)然后您将此Reset 属性设置为true,您的ScrollViewer 将滚动到顶部。
我已将AtachedProperty命名为 AutoScrollToTop,但名称对于此目的并不重要。
XAML 将类似于:
<ScrollViewer my:ScrollViewerBehavior.AutoScrollToTop="{Binding Reset, Mode=TwoWay}">
<ListView>
<ListView.View>
<GridView>
<GridViewColumn
Header = "Name"
DisplayMemberBinding="{Binding Path=Name}"
/>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
注意:my 是您的 ScrollViewerBehavior 类所在的命名空间。例如:xmlns:my="clr-namespace:MyApp.Behaviors"
最后,您在 ViewModel 中唯一需要做的就是在您喜欢时设置Reset = true,在您的情况下,当您从集合中添加或删除元素时。