简体   繁体   中英

WPF ListBox AutoScroll Stops Working

I am creating a GUI for a console application and want the output to display in a ListBox. If I type "time" into a textbox and click the button that Says "Send" the command is sent to the console app. The problem is that the listbox stops scrolling down automatically when commands are sent. Am I doing something incorrectly or is there another way autoscrolling should be handled?

While the application is loading it scrolls properly

滚动工作

After the application loads the scroll stops working

在此处输入图片说明

After the application gets the command it adds an item to the listbox which causes the AutoScroll method to run but even though the code executes the listbox does not scroll down. I've tried adding a call to AutoScroll after the commands are sent but that does not work either.

    private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        server = new Server();
        string ExecPath = @"Server.exe";
        string ConfPath = @"serverconfig.txt";

        //Starts the process and passes the config cmd-line argument
        //redirects output and input, and prevents a cmd window from being created
        server.Start(ExecPath, ConfPath);
        server.SrvProcess.OutputDataReceived += SrvProcess_OutputDataReceived;
        server.SrvProcess.BeginOutputReadLine();
    }

    private void btnSend_Click(object sender, RoutedEventArgs e)
    {
        int itemCount = lstOutput.Items.Count;

        if (!String.IsNullOrEmpty(txtCmd.Text))
        {
            if (lstOutput.Items[itemCount - 1].ToString() != String.Empty)
                lstOutput.Items.Add(String.Empty);

            lstOutput.Items.Add(": " + txtCmd.Text);
            server.SrvProcess.StandardInput.WriteLine(txtCmd.Text);
        }
    }

    void SrvProcess_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
    {
        if (!closing)
        {
            lstOutput.Dispatcher.Invoke(() => AddItem(e.Data));
            lstOutput.Dispatcher.InvokeAsync(() => AutoScroll());
        }
    }

    void AddItem(string Data)
    {
        lstOutput.Items.Add(Data);
        if (Data == "Server started")
        {
            lstOutput.Items.Clear();
        }
    }

    void AutoScroll()
    {
        int itemCount = lstOutput.Items.Count - 1;
        if (itemCount > -1)
            lstOutput.ScrollIntoView(lstOutput.Items[itemCount]);
    }

ScrollIntoView appears to use the text of the line to determine where to scroll. By adding a timestamp to make every line unique the scrolling will work properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM