简体   繁体   中英

Events in hierarchical tree of User Controls

Good day. Program in C#, I need hierarchical tree of UserControls. I used following:

public class MyControl : UserControl //my own control
{
    this.MouseClick += new System.Windows.Forms.MouseEventHandler(SomeMethodForProcessing);
}

public class TreeNode<T> //universal tree data structure
{
    List<TreeNode<T>> childs;
    T data;
}

TreeNode<MyControl> tree; //using my tree

But I need to process my tree depends on user interaction with my controls, for example, user click the control and TreeNode with this control is deleted. Please tell me, how can I do it? May be I must use another approach like this:

public class MyControl : UserControl //my control and at the same time tree
{
    List<MyControl> childs;
}

MyControl root; //using my tree

Or is there another way?

If I understand your question correctly, this could be an approach:

public class YourNode : TreeNode
{
    public Control Control { get; set; }
}

Another way is to use the Tag-Property of the TreeNode-Class. But I'd prefer the first approach.

Each tree node have own events that has handled by tree control. for example when your mouse goes on any node then MouseHover event will be executed in that tree node not directly in Tree control. So, you have to create an event in treenode then you can handle tree control event from here. for example

private TreeNode_Click(object sender, EventArgs e)
{
    If (MyControl.ItemClicked != null)    
        MyControl.ItemClicked(this, e);
}

UPDATE:

this code will be written in your form. the event will be added in your form. But you must have declared event in MyControl user control.

private MyControl_ItemClicked(object sender, EventArgs e)
{
    if (sender != null)
        this.Nodes.Remove((TreeNode)sender);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM