在ListBox中添加一條記錄(ListBox.Items.Add方法)后,滾動條會自動回到頂部。我們可能更希望它自動滾動到底部,簡要介紹幾種方法。
方法一:
1 this.listBox1.Items.Add("new line"); 2 this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1; 3 this.listBox1.SelectedIndex = -1;
在添加記錄后,先選擇最后一條記錄,滾動條會自動到底部,再取消選擇。
缺點是需兩次設置選中條目,中間可能會出現反色的動畫,影響美觀。
方法二:
1 this.listBox1.Items.Add("new line"); 2 this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
通過計算ListBox顯示的行數,設置TopIndex屬性(ListBox中第一個可見項的索引)而達到目的。
方法二 plus:智能滾動
1 bool scroll = false; 2 if(this.listBox1.TopIndex == this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight)) 3 scroll = true; 4 this.listBox1.Items.Add("new line"); 5 if (scroll) 6 this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
在添加新記錄前,先計算滾動條是否在底部,從而決定添加后是否自動滾動。
既可以在需要時實現自動滾動,又不會在頻繁添加記錄時干擾用戶對滾動條的控制。
