Reputation: 107
The text in my TextBlock is bound to an element in my code. However, when I first open my window, the Textblock is completely empty. As I add text, I need the ScrollViewer to allow me to scroll down the text, or automatically scroll down as more text is added. Using the MVVM, so no code behind would be ideal.
<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>
How can I make this happen? Is there a way to update the ScrollViewer so that it sees more text is beyond what I can see in the TextBlock and allows the user to scroll down, or allows me to set an autoscroll feature that scrolls down automatically as text is added via binding?
Thanks in advance!
Upvotes: 1
Views: 717
Reputation: 13
One more variant with Microsoft.Xaml.Behaviors.Wpf.
No code behind!
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>
Upvotes: 0
Reputation: 35680
scrollbar will work if you remove Height="100"
from TextBlock
to make it scroll when Text changes other answers suggest to use ScrollViwer.ScrollToBottom() method, e.g. like this:
<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();
}
Upvotes: 1