如何使用 Xaml 和绑定自动滚动到 ScrollViewer 的底部? [英] How to scroll to the bottom of a ScrollViewer automatically with Xaml and binding?

查看:25
本文介绍了如何使用 Xaml 和绑定自动滚动到 ScrollViewer 的底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextBlock,它的内容是绑定到 ViewModel 字符串属性的数据.这个 TextBlock 有一个 ScrollViewer 包裹在它周围.

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.

我想要做的是每次日志更改时,ScrollViewer 将滚动到底部.理想情况下,我想要这样的东西:

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>

不想想使用隐藏代码!我正在寻找的解决方案应该使用绑定和/或 Xaml.

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.

附加属性

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();
        }
    }
}

Xaml 绑定

<ScrollViewer local:Helper.AutoScroll="{Binding IsLogsChangedPropertyInViewModel}" .../>

您需要创建一个布尔属性 IsLogsChangedPropertyInViewModel 并在更改字符串属性时将其设置为 true.

You will need to create a boolean property IsLogsChangedPropertyInViewModel and set it to true when the string property is changed.

希望这有帮助!:)

这篇关于如何使用 Xaml 和绑定自动滚动到 ScrollViewer 的底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆