從Geoff's Blog on ScrollViewer AutoScroll Behavior。
加入這個類:
namespace MyAttachedBehaviors
{
/// <summary>
/// Intent: Behavior which means a scrollviewer will always scroll down to the bottom.
/// </summary>
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);
}
}
}
}
此代碼取決於混合行爲,需要以System.Windows.Interactivity
參考。見help on adding System.Windows.Interactivity
。
如果您安裝了MVVM光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
的內容打印到屏幕上,這非常適合記錄。
沒有代碼背後的任何具體原因? –
我猜這是一個宗教信仰,背後的代碼和MVVM不應該混合。 –
你是對的,但在我看來,MVVM只建議你的業務邏輯(視圖模型)不應該與你的用戶界面(視圖)混合。滾動查看器是用戶界面/視圖,如果我們在後面的代碼中放置一些代碼將ScrollViewer移動到底部,它不會反對MVVM,因爲我們只是玩UI –