How do I create an Autoscrolling TextBox

前端 未结 6 1340
囚心锁ツ
囚心锁ツ 2021-01-31 04:02

I have a WPF application that contains a multiline TextBox that is being used to display debugging text output.

How can I set the TextBox so that as text is appended to

6条回答
  •  北海茫月
    2021-01-31 04:34

    Similar answer to the other answers, but without the statics events and control dictionary. (IMHO, static events are best avoided if possible).

    public class ScrollToEndBehavior
    {
        public static readonly DependencyProperty OnTextChangedProperty =
                    DependencyProperty.RegisterAttached(
                    "OnTextChanged",
                    typeof(bool),
                    typeof(ScrollToEndBehavior),
                    new UIPropertyMetadata(false, OnTextChanged)
                    );
    
        public static bool GetOnTextChanged(DependencyObject dependencyObject)
        {
            return (bool)dependencyObject.GetValue(OnTextChangedProperty);
        }
    
        public static void SetOnTextChanged(DependencyObject dependencyObject, bool value)
        {
            dependencyObject.SetValue(OnTextChangedProperty, value);
        }
    
        private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var textBox = dependencyObject as TextBox;
            var newValue = (bool)e.NewValue;
    
            if (textBox == null || (bool)e.OldValue == newValue)
            {
                return;
            }
    
            TextChangedEventHandler handler = (object sender, TextChangedEventArgs args) =>
                ((TextBox)sender).ScrollToEnd();
    
            if (newValue)
            {
                textBox.TextChanged += handler;
            }
            else
            {
                textBox.TextChanged -= handler;
            }
        }
    }
    

    This is just an alternative to the other posted solutions, which were among the best I found after looking for awhile (i.e. concise & mvvm).

提交回复
热议问题