来自Geoff博客关于ScrollViewer自动滚动行为的文章.
添加这个类:
namespace MyAttachedBehaviors
{
public class AutoScrollBehavior : Behavior<ScrollViewer>
{
private double _height = 0.0d;
private ScrollViewer _scrollViewer = null;
protected override void OnAttached()
{
base.OnAttached();
this._scrollViewer = base.AssociatedObject;
this._scrollViewer.LayoutUpdated += new EventHandler(_scrollViewer_LayoutUpdated);
}
private void _scrollViewer_LayoutUpdated(object sender, EventArgs e)
{
if (Math.Abs(this._scrollViewer.ExtentHeight - _height) > 1)
{
this._scrollViewer.ScrollToVerticalOffset(this._scrollViewer.ExtentHeight);
this._height = this._scrollViewer.ExtentHeight;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (this._scrollViewer != null)
{
this._scrollViewer.LayoutUpdated -= new EventHandler(_scrollViewer_LayoutUpdated);
}
}
}
}
这段代码依赖于 Blend Behaviors,需要引用 System.Windows.Interactivity
。请参考添加 System.Windows.Interactivity
的帮助。
如果你安装了 MVVM Light NuGet 包,可以在此处添加引用:
packages\MvvmLightLibs.4.2.30.0\lib\net45\System.Windows.Interactivity.dll
请确保您的标头中包含此属性,该属性指向 System.Windows.Interactivity.dll
:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
在ScrollViewer
中添加混合行为:
<i:Interaction.Behaviors>
<implementation:AutoScrollBehavior />
</i:Interaction.Behaviors>
例子:
<GroupBox Grid.Row="2" Header ="Log">
<ScrollViewer>
<i:Interaction.Behaviors>
<implementation:AutoScrollBehavior />
</i:Interaction.Behaviors>
<TextBlock Margin="10" Text="{Binding Path=LogText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap"/>
</ScrollViewer>
</GroupBox>
我们需要为命名空间添加一个定义,否则它就不知道在哪里找到我们刚刚添加的C#类。将这个属性添加到<Window>
标记中。如果你使用的是ReSharper,它会自动为你建议。
xmlns:implementation="clr-namespace:MyAttachedBehaviors"
现在,如果一切顺利,框中的文本将始终滚动到底部。
所提供的XAML示例将打印绑定属性LogText的内容到屏幕上,这非常适合记录日志。