Multiline Textbox with automatic vertical scroll

后端 未结 4 1411
清酒与你
清酒与你 2020-12-14 05:37

There are a lot of similiar questions over internet, on SO included, but proposed solutions doesn\'t work in my case. Scenario : there is a log textbox in xaml



        
4条回答
  •  攒了一身酷
    2020-12-14 06:13

    If you don't like code behind to much, here is an AttachedProperty that will do the trick :

    namespace YourProject.YourAttachedProperties
    {
    
        public class TextBoxAttachedProperties
        {
    
            public static bool GetAutoScrollToEnd(DependencyObject obj)
            {
                return (bool)obj.GetValue(AutoScrollToEndProperty);
            }
    
            public static void SetAutoScrollToEnd(DependencyObject obj, bool value)
            {
                obj.SetValue(AutoScrollToEndProperty, value);
            }
    
            // Using a DependencyProperty as the backing store for AutoScrollToEnd.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty AutoScrollToEndProperty =
            DependencyProperty.RegisterAttached("AutoScrollToEnd", typeof(bool), typeof(TextBoxAttachedProperties), new PropertyMetadata(false, AutoScrollToEndPropertyChanged));
    
            private static void AutoScrollToEndPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if(d is TextBox textbox && e.NewValue is bool mustAutoScroll && mustAutoScroll)
                {
                    textbox.TextChanged += (s, ee)=> AutoScrollToEnd(s, ee, textbox);
                }
            }
    
            private static void AutoScrollToEnd(object sender, TextChangedEventArgs e, TextBox textbox)
            {
                textbox.ScrollToEnd();
            }
        }
    }
    

    And then in your xaml just do :

    
    

    Just don't forget to add at the top of your xaml file

    xmlns:myAttachedProperties="clr-namespace:YourProject.YourAttachedProperties"
    

    And voila

提交回复
热议问题