C#中listBox實現自動滾動到底部的效果

背景:在ListBox中添加一條記錄(ListBox.Items.Add方法)後,滾動條會自動回到頂部。我們可能更希望它自動滾動到底部,本文簡要介紹幾種方法。


方法一:

this.listBox1.Items.Add("new line");
this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1;
this.listBox1.SelectedIndex = -1;


在添加記錄後,先選擇最後一條記錄,滾動條會自動到底部,再取消選擇。缺點是需兩次設置選中條目,中間可能會出現反色的動畫,影響美觀。


方法二:

this.listBox1.Items.Add("new line");
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);


通過計算ListBox顯示的行數,設置TopIndex屬性(ListBox中第一個可見項的索引)而達到目的。


方法三: 智能滾動

bool scroll = false;
if(this.listBox1.TopIndex == this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight))
scroll = true;
this.listBox1.Items.Add("new line");
if (scroll)
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);


在添加新記錄前,先計算滾動條是否在底部,從而決定添加後是否自動滾動。

既可以在需要時實現自動滾動,又不會在頻繁添加記錄時干擾用戶對滾動條的控制。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章