我的 TextBlock 中的文本绑定到我的代码中的一个元素。但是,当我第一次打开窗口时,文本块完全是空的。添加文本时,我需要 ScrollViewer 来允许我向下滚动文本,或者在添加更多文本时自动向下滚动。使用 MVVM,因此没有代码隐藏是理想的选择。
<StackPanel Grid.Column="0" Grid.Row="1" Margin="0 10">
<Label Style="{StaticResource LabelStyle}">Output</Label>
<ScrollViewer VerticalScrollBarVisibility="Visible" Height="100">
<TextBlock ScrollViewer.CanContentScroll="True" Height="100" VerticalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding Path=ProcessingOutput}"/>
</ScrollViewer>
</StackPanel>
我怎样才能做到这一点?有没有办法更新 ScrollViewer,以便它看到更多文本超出我在 TextBlock 中看到的范围,并允许用户向下滚动,或者允许我设置自动滚动功能,在通过绑定添加文本时自动向下滚动?
提前致谢!
Height="100"
TextBlock
,滚动条将起作用
要使其在文本更改时滚动,其他答案建议使用 ScrollViwer.ScrollToBottom() 方法,例如像这样:
<ScrollViewer Name="scroll"
VerticalScrollBarVisibility="Visible"
Height="100">
<TextBlock ScrollViewer.CanContentScroll="True"
VerticalAlignment="Stretch"
TextWrapping="Wrap"
Text="{Binding Path=ProcessingOutput, NotifyOnTargetUpdated=True}"
TargetUpdated="Txt_OnTargetUpdated">
</TextBlock>
</ScrollViewer>
private void Txt_OnTargetUpdated(object sender, DataTransferEventArgs e)
{
scroll.ScrollToBottom();
}
还有一个变体 Microsoft.Xaml.Behaviors.Wpf.
无代码隐藏!
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
<ScrollViewer Name="TextScrollViewer">
<TextBlock TextWrapping="Wrap" Text="{Binding MessageText, NotifyOnTargetUpdated=True}"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="TargetUpdated">
<i:CallMethodAction MethodName="ScrollToBottom" TargetObject="{Binding ElementName=TextScrollViewer}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ScrollViewer>