【问题标题】:Scroll wpf textblock to end滚动 wpf 文本块到结束
【发布时间】:2013-02-03 18:27:28
【问题描述】:

TextBlock 是否有任何允许始终滚动到末尾的功能?

我在后面的代码中看到了很多这样的例子,

我要保持MVVM的原理,不碰后面的代码,

我正在XAML 中寻找一种方法来执行此操作。

有吗?

【问题讨论】:

    标签: wpf mvvm binding datagrid


    【解决方案1】:

    我假设您的 TextBlock 嵌套在 ScrollViewer 中。在这种情况下,您将不得不创建一个附加属性。请参阅此相关问题:

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

    即创建附加属性:

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

    然后绑定如下:

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

    【讨论】:

    • 没有办法只在 XAML 中执行此操作吗?这是最简单的方法..?
    • @HodayaShalom 不,这不是平台支持的功能。你需要写一些代码!
    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多