樹形控制項是使用頻率很高的一種控制項。對於屬性控制項往往需要下面兩個功能
1.TreeList帶有CheckBox,並且節點要有三種狀態(所有的子節點都選中,所有的子節點都沒選擇,一部分子節點選中)。使用DevXpress的TreeList控制項很容易實現這一功能。
設定TreeList.OptionsView.ShowCheckBoxes = true //是否顯示CheckBox
設定TreeList.OptionsBehavior.AllowIndeterminateCheckState = true; //設定節點是否有中間狀態,即一部分子節點選中,一部分子節點沒有選中
設定這兩個屬性之後就實現了TreeList帶有CheckBox,並且節點有三種狀態。
2.選中父節點或者子節點相互影響的功能,如選擇父節點選擇所有子節點。綁定TreeList的兩個事件AfterCheckNode和BeforeCheckNode
實現功能的代碼如下:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
SetCheckedChildNodes(e.Node, e.Node.CheckState);
SetCheckedParentNodes(e.Node, e.Node.CheckState);
}
private void treeList1_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
{
e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
}
/// <summary>
/// 設定子節點的狀態
/// </summary>
/// <param name="node"></param>
/// <param name="check"></param>
private void SetCheckedChildNodes(TreeListNode node, CheckState check)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
node.Nodes[i].CheckState = check;
SetCheckedChildNodes(node.Nodes[i], check);
}
}
/// <summary>
/// 設定父節點的狀態
/// </summary>
/// <param name="node"></param>
/// <param name="check"></param>
private void SetCheckedParentNodes(TreeListNode node, CheckState check)
{
if (node.ParentNode != null)
{
bool b = false;
CheckState state;
for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
{
state = (CheckState)node.ParentNode.Nodes[i].CheckState;
if (!check.Equals(state))
{
b = !b;
break;
}
}
node.ParentNode.CheckState = b ? CheckState.Indeterminate : check;
SetCheckedParentNodes(node.ParentNode, check);
}
}
============================================================================
1.TreeList.NodeCellStyle事件
Node的顯示(包括視窗的切換導致Node的顯示)和狀態的改變都會觸發該事件。該事件主要用來改變Node的顯示樣式。
private void treeList1_NodeCellStyle(object sender, DevExpress.XtraTreeList.GetCustomNodeCellStyleEventArgs e)
{
if (e.Node.CheckState == CheckState.Unchecked)
{
e.Appearance.Font = new Font(DevExpress.Utils.AppearanceObject.DefaultFont, FontStyle.Strikeout);
e.Appearance.ForeColor = Color.Gray;
}
}
上面的代碼是實現的效果是 : CheckState為Unchecked的節點的字帶有中劃線且背景灰色。
2.TreeList.DoubleClick事件
雙擊Node時觸發,但要注意的是要在TreeList.OptionsBehavior.Editable = false的情況下,雙擊Node才能觸發該事件。
private void treeList1_DoubleClick(object sender, EventArgs e)
{
TreeListNode clickedNode = this.treeList1.FocusedNode;
string disPlayText = clickedNode.GetDisplayText("test");
MessageBox.Show("You clicked " + disPlayText);
}
3.TreeList的點擊測試特性
private void treeList1_MouseMove(object sender, MouseEventArgs e)
{
Point point = treeList1.PointToClient(Cursor.Position);
TreeListHitInfo hitInfo = treeList1.CalcHitInfo(point);
switch (hitInfo.HitInfoType)
{
case HitInfoType.Cell:
this.Cursor = Cursors.Hand;
break;
case HitInfoType.NodeCheckBox:
this.Cursor = Cursors.PanEast;
break;
default :
this.Cursor = Cursors.Default;
break;
}
}