[英]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.