繁体   English   中英

WPF ListBox AutoScroll停止工作

[英]WPF ListBox AutoScroll Stops Working

我正在为控制台应用程序创建GUI,并希望输出显示在ListBox中。 如果我在文本框中输入“时间”并单击“发送”按钮,则命令将发送到控制台应用程序。 问题是发送命令时,列表框会自动停止向下滚动。 我做错了什么吗?还是应该采用另一种方式处理自动滚动?

在应用程序加载时,它可以正确滚动

滚动工作

应用程序加载后,滚动停止工作

在此处输入图片说明

应用程序获取命令后,它将在列表框中添加一个项目,这将导致AutoScroll方法运行,但是即使代码执行了该列表框也不会向下滚动。 我已经尝试在命令发送后向AutoScroll添加一个调用,但这也不起作用。

    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似乎使用该行的文本来确定滚动位置。 通过添加时间戳以使每一行都唯一,滚动将正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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