[英]Appending text to a line in a listbox
有沒有辦法將文本追加到ListBox的最后一行? 我希望列表看起來像這樣:
processing file 1... OK
processing file 2... CRC error
processing file 3... OK
當我打開文件進行處理時,我會用ListBox.Add(“處理文件x”)寫“處理文件x”。 完成處理后,在繼續下一個文件之前,我想附加處理結果。
我可以等到處理完成,然后立即寫入整行,但處理文件可能需要10-15秒,這會使UI看起來沒有響應。
一個解決方案還允許我附加文本(如完成%)或其他東西,以使UI在處理時更加活躍。 我更喜歡使用ListBox,因為它的滾動和行選擇屬性,如果可能的話。
我找不到任何方法可以做到這一點; 任何想法都會受到歡迎。
您可以直接將項目添加到列表框中
listBox1.Items.Add("new item");
你可能需要刷新它
listBox1.Refresh();
編輯:
如果要更新最后一項,則需要刪除最后一項,然后重新添加
var lastItem= listBox1.Items[listBox1.Items.Count-1];
lastItem += results;
listBox1.Items.RemoveAt(listBox1.Items.Count-1);
listBox1.Add(lastItem);
您的問題是GUI事件在與GUI呈現相同的線程上處理,因此UI將無響應,直到完成為止。
快速而苛刻的解決方案是在每次ListBox.Add調用之后調用Application.DoEvents() 。 如果您嘗試拖動它,表單仍然會抖動,但該功能將導致GUI更新/渲染一次。
正確的方法是使用BackgroundWorker ,您可以從GUI事件開始,並在后台處理單獨的線程。 如果實現其ProgressChanged函數,可以從DoWork調用它:
(sender as BackgroundWorker).ReportProgress(i/(float)totalFiles,msgString)
然后在ProgressChanged中,做你的整個:
listBox.Add(e.UserState.ToString() + ", " + e.ProgressPercentage.ToString() + "% completed.")
簡單版本:
var i = listBox.Items.Count - 1; // crash bug if there is no line to append to
listBox.Items[i] = listBox.Items[i] + message;
或者,對於更完整的解決方案(從非UI線程工作):
public static class Util
{
public static async Task RunOnUiThread(Action a)
{
await Application.Current.Dispatcher.InvokeAsync(() => { a(); });
}
}
public partial class MainWindow : Window
{
private async Task Write(string message)
{
var action = new Action(() =>
{
var i = OutputListBox.Items.Count - 1;
if (i >= 0)
{
OutputListBox.Items[i] = OutputListBox.Items[i] + message;
}
else
{
OutputListBox.Items.Add(message);
}
});
await Util.RunOnUiThread(action);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.