Ramzy Abourafeh
Ramzy Abourafeh

Reputation: 1195

ScrollViewer Control in Wpf

<ScrollViewer VerticalScrollBarVisibility="Auto" >
 <TextBlock Text="{Binding Status}"
            HorizontalAlignment="Center" />
</ScrollViewer>

The Status always I'm adding to it, that is to say that in the code behind always I do this thing:

Status+= Environment.NewLine + "Hi";

And the ScrollViewer increasing, but the Status that I see is the first one, when I want to see the last one I need to scroll underneath to see it, my question is: how I can made the Scrollviewer scrolling underneath automaticaly?, that meaning I want always see the last status not the first.

Sorry about the broken english.

Upvotes: 0

Views: 460

Answers (1)

Charles Josephs
Charles Josephs

Reputation: 1535

Name your ScrollViewer so you can access it in the code behind, like this:

<ScrollViewer x:Name="MyScrollViewer" VerticalScrollBarVisibility="Auto" >
 <TextBlock Text="{Binding Status}"
        HorizontalAlignment="Center" />
</ScrollViewer>

Then you can do this:

Status+= Environment.NewLine + "Hi";
MyScrollViewer.ScrollToEnd(); 

With the way I do MVVM, I have access to my ViewModel from my View, so when the View first loads, I'd subscribe to the PropertyChanged event on my ViewModel as so:

MyViewModel.PropertyChanged += ViewModelChanged;

and then in the ViewModelChanged callback I'd have this:

private void ViewModelChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Status")
        MyScrollViewer.ScrollToEnd();
}

Every time the ViewModel's Status property changes, the ScrollViewer will now scroll to end. Just remember to unsubscribe from MyViewModel.PropertyChanged when you leave that screen to avoid a memory leak.

Upvotes: 1

Related Questions