Search code examples
c#wpfxamltextbox

Textbox in scrollviewer delete outdated lines in wpf


I'm still new in wpf so please bear with me.

I have a GroupBox that handle my logging. inside of it is ScrollViewer for scrolling and a TextBox to contain the logging. what i want is that at certain number of lines i want to delete the topmost part of the lines so that the textbox doesn't get overwhelmed by all logging information. I just want to know if there's a way to approach this or am I missing some information.

          <GroupBox Header="Logs" Grid.Row="0" Height="300" >
              <ScrollViewer x:Name="LogScrollViewer" CanContentScroll="True" 
                        HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" >
                  <TextBox x:Name="LogTextBox" IsReadOnly="True"
                              AcceptsReturn="True" TextWrapping="Wrap"/>
              </ScrollViewer>
          </GroupBox>

I did try to use a solution gemini proposed to me below in my xaml.cs, but it keeps return an error CS1061 at the LogTextBox.Lines and I don't know if I'm missing any dependencies, or I do something wrong or it's just a wrong approach in the first place.

        if (LogTextBox.LineCount > 300)
        {
            string[] lines = LogTextBox.Lines;

            string[] trimmedLines = new string[300];
            Array.Copy(lines, lines.Length - 300, trimmedLines, 0, 300);

            LogTextBox.Lines = trimmedLines;
        }


Solution

  • What works for me after changing a bit of the code from @Danial

    int lineCount = LogTextBox.LineCount;
    if (lineCount > 300)
    {
         int excessLines = lineCount - 300;
    
         var text = LogTextBox.Text;
         int removeIndex = 0;
    
         for (int i = 0; i < excessLines; i++)
         {
         removeIndex = text.IndexOf(Environment.NewLine, removeIndex) + 
         Environment.NewLine.Length;
         }
    LogTextBox.Text = text.Substring(removeIndex);
    }