I've got a TextBlock
whose content is data bound to a string property of the ViewModel. This TextBlock
has a ScrollViewer
wrapped around it.
What I want to do is every time the logs change, the ScrollViewer
will scroll to the bottom. Ideally I want something like this:
<ScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollPosition="{Binding Path=ScrollPosition}">
<TextBlock Text="{Binding Path=Logs}"/>
</ScrollViewer>
I don't want to use Code Behind! The solution I'm looking for should be using only binding and/or Xaml.
You can either create an attached property or a behavior to achieve what you want without using code behind. Either way you will still need to write some code.
Here is an example of using attached property.
Attached Property
Xaml Binding
You will need to create a boolean property
IsLogsChangedPropertyInViewModel
and set it to true when the string property is changed.Hope this helps! :)
I was using @Roy T. 's answer, however I wanted the added stipulation that if you scrolled back in time, but then added text, the scroll view should auto scroll to bottom.
I used this:
in place of the SizeChanged event.
From Geoff's Blog on ScrollViewer AutoScroll Behavior.
Add this class:
This code depends Blend Behaviors, which require a reference to
System.Windows.Interactivity
. See help on addingSystem.Windows.Interactivity
.If you install the MVVM Light NuGet package, you can add a reference here:
Ensure that you have this property in your header, which points to
System.Windows.Interactivity.dll
:Add a Blend Behavior into the
ScrollViewer
:Example:
We have to add a definition for the namespace, or else it won't know where to find the C# class we have just added. Add this property into the
<Window>
tag. If you are using ReSharper, it will automatically suggest this for you.Now, if all goes well, the text in the box will always scroll down to the bottom.
The example XAML given will print the contents of the bound property
LogText
to the screen, which is perfect for logging.Here is a slight variation.
This will scroll to the bottom both when the scroll viewer height (viewport) and the height of it's scroll presenter's content (extent) change.
It's based on Roy T's answer but I wasn't able to comment so I have posted as an answer.
It is easy, examples:
Answer updated 2017-12-13, now uses the ScrollChanged event and checks if the size of extent changes. More reliable and doesn't interfere with manual scrolling
I know this question is old, but I've got an improved implementation:
The code is heavily influenced by Both Justin XL's and Contango's solutions
Usage: