本文轉載:http://www.cnblogs.com/umplatform/archive/2012/08/29/2660240.html
在B/S開發中,對TreeView控件要改變當前選中節點的顏色比較方便,其有相應的SelectedNodeChanged事件進行控制,但對於WinForm則沒有這樣方便。申明一下,我在這兒所說的改變當前節點的字體與顏色,主要是在WinForm中的TreeView控件,當前選中節點后,其失去鼠標焦點后節點的字體與顏色失去了選中狀態,層級一多,我們就不知道當前選擇的是那個節點了。用戶體驗性稍微欠缺一些。其實實現方法非常簡單,主要用到TreeView的兩個事件,分別為:BeforeSelect與AfterSelect事件。代碼如下:
TreeNode theLastNode = null;//最后選擇的節點(用於還原節點狀態)
private void tvCustomerClass_AfterSelect(object sender, TreeViewEventArgs e)
{
if (this.tvCustomerClass.SelectedNode != null)
{
theLastNode = tvCustomerClass.SelectedNode;
}
}
private void tvCustomerClass_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
e.Node.ForeColor = Color.Blue;
e.Node.NodeFont = new Font("宋體", 10, FontStyle.Underline|FontStyle.Bold);
if (theLastNode != null)
{
theLastNode.ForeColor = SystemColors.WindowText;
theLastNode.NodeFont = new Font("宋體", 11, FontStyle.Regular);
}
}
{
if (this.tvCustomerClass.SelectedNode != null)
{
theLastNode = tvCustomerClass.SelectedNode;
}
}
private void tvCustomerClass_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
e.Node.ForeColor = Color.Blue;
e.Node.NodeFont = new Font("宋體", 10, FontStyle.Underline|FontStyle.Bold);
if (theLastNode != null)
{
theLastNode.ForeColor = SystemColors.WindowText;
theLastNode.NodeFont = new Font("宋體", 11, FontStyle.Regular);
}
}
效果如下:
如上圖所示,我們當前選擇的節點是“所有分類”下的“地區”,字體顏色改了,當其失去焦點后我們同樣可以很清楚的知道當前選擇的分類。