【问题标题】:WPF ListBox AutoScroll Stops WorkingWPF ListBox AutoScroll 停止工作
【发布时间】:2013-05-25 02:37:58
【问题描述】:

我正在为控制台应用程序创建一个 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]);
    }

【问题讨论】:

    标签: c# wpf listbox


    【解决方案1】:

    ScrollIntoView 似乎使用该行的文本来确定滚动的位置。通过添加时间戳使每一行都是唯一的,滚动将正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多