Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll wpf textblock to end

Is there any feature of the TextBlock that allows scrolling to the end always?

I've seen a number of examples that do this in the code behind,

I want to keep the principle of MVVM and not touch the code behind,

I'm looking for a way to do this in XAML.

Have one?

like image 318
Hodaya Shalom Avatar asked Apr 17 '26 06:04

Hodaya Shalom


1 Answers

I am assuming your TextBlock is nested within a ScrollViewer. In this case you are going to have to create an attached property. See this related question:

How to scroll to the bottom of a ScrollViewer automatically with Xaml and binding?

i.e. create an attached property:

public static class Helper
{
    public static bool GetAutoScroll(DependencyObject obj)
    {
        return (bool)obj.GetValue(AutoScrollProperty);
    }

    public static void SetAutoScroll(DependencyObject obj, bool value)
    {
        obj.SetValue(AutoScrollProperty, value);
    }

    public static readonly DependencyProperty AutoScrollProperty =
        DependencyProperty.RegisterAttached("AutoScroll", typeof(bool), typeof(Helper), new PropertyMetadata(false, AutoScrollPropertyChanged));

    private static void AutoScrollPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = d as ScrollViewer;

        if (scrollViewer != null && (bool)e.NewValue)
        {
            scrollViewer.ScrollToBottom();
        }
    }
}

Then bind as follows:

<ScrollViewer local:Helper.AutoScroll="{Binding BooleanViewModelPropertyThatTriggersScroll}" .../>
like image 62
ColinE Avatar answered Apr 19 '26 10:04

ColinE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!