I ran into a bit of a problem when attempting to leverage the usage of textboxes in WPF. Prior before tackling WPF applications (which is something I’m still learning to utilize), I primarily created WFA applications to create tools that I might use to make life easier. I started to hit a few dislikes with WFA which led me to begin developing WPF applications instead.

My goal in this program was simply to have a line limit of 20, and after the line count exceeded that threshold, it would remove the line at element 0. With WFA it was relatively simple with the provided code below:

public void AppendTextBetter(string text, ListBox logbox)
        {
            if (logbox.Items.Count > 20)
            {
                logbox.Items.RemoveAt(logbox.Items.Count-1);
                logbox.Items.Insert(0, text);
            }
            else
            {
                logbox.Items.Insert(0, text);
            }
        }

Now, with WPF I had to tackle the approach a little differently and searching around I couldn’t find too many helpful resources on this task. However, I found a means to program a way to create the same functionality. I used a SubArray extension from another post I found, and with that, I implemented it into the WPF program.

private void textChanged(object sender, TextChangedEventArgs e)
        {
            if (textBox.LineCount > maxLines)
            {
                string[] arrLines = textBox.Text.Split('\n').ToArray();
                arrLines = test.SubArray(arrLines, 1, maxLines - 1);
                textBox.Text = "";

                foreach (string s in arrLines)
                {
                    textBox.Text += s + "\n";
                }
            }
        }

The extension method:
Credit to the poster on this thread – SubArray Link

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
    T[] arrCopy = new T[length];
    Array.Copy(data, index, arrCopy, 0, length);
    using (MemoryStream ms = new MemoryStream())
    {
        var bf = new BinaryFormatter();
        bf.Serialize(ms, arrCopy);
        ms.Position = 0;
        return (T[])bf.Deserialize(ms);
    }
}