Scroll wpf textblock to end

浪子不回头ぞ 提交于 2020-02-28 07:30:58

问题


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?


回答1:


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}" .../>


来源:https://stackoverflow.com/questions/14951302/scroll-wpf-textblock-to-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!