How do I create an Autoscrolling TextBox

前端 未结 6 1344
囚心锁ツ
囚心锁ツ 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:51

    Hmm this seemed like an interesting thing to implement so I took a crack at it. From some goggling it doesn't seem like there is a straight forward way to "tell" the Textbox to scroll itself to the end. So I thought of it a different way. All framework controls in WPF have a default Style/ControlTemplate, and judging by the looks of the Textbox control there must be a ScrollViewer inside which handles the scrolling. So, why not just work with a local copy of the default Textbox ControlTemplate and programmaticlly get the ScrollViewer. I can then tell the ScrollViewer to scroll its Contents to the end. Turns out this idea works.

    Here is the test program I wrote, could use some refactoring but you can get the idea by looking at it:

    Here is the XAML:

    
      
        
        
        
        
        
        
          
            
          
          
            
              
              
              
            
          
        
        
    
      
      
        test
      
    
    

    And the code behind:

    using System;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace WpfApplication3
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                for (int i = 0; i < 10; i++)
                {
                    textbox.AppendText("Line " + i + Environment.NewLine);
                }
            }
        }
    
        public class AutoScrollTextBox : TextBox
        {
            protected override void OnTextChanged(TextChangedEventArgs e)
            {
                base.OnTextChanged(e);
                // Make sure the Template is in the Visual Tree: 
                // http://stackoverflow.com/questions/2285491/wpf-findname-returns-null-when-it-should-not
                ApplyTemplate();
                var template = (ControlTemplate) FindResource("MyTextBoxTemplate");
                var scrollViewer = template.FindName("PART_ContentHost", this) as ScrollViewer;
                //SelectionStart = Text.Length;
                scrollViewer.ScrollToEnd();
            }
        }
    }
    

提交回复
热议问题