C# 用户控件的层次结构树中的事件

C# 用户控件的层次结构树中的事件,c#,user-controls,tree,C#,User Controls,Tree,你好。在C#程序中,我需要用户控件的层次结构树。我使用了以下方法: public class MyControl : UserControl //my own control { this.MouseClick += new System.Windows.Forms.MouseEventHandler(SomeMethodForProcessing); } public class TreeNode<T> //universal tree data structure {

你好。在C#程序中,我需要用户控件的层次结构树。我使用了以下方法:

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
公共类MyControl:UserControl//我自己的控件
{
this.MouseClick+=new System.Windows.Forms.MouseEventHandler(SomeMethodForProcessing);
}
公共类树节点//通用树数据结构
{
列出儿童;
T数据;
}
树形树//使用我的树
但是我需要处理我的树,这取决于用户与我的控件的交互,例如,用户单击该控件,则删除带有该控件的树节点。请告诉我,我怎么做?也许我必须使用另一种方法,比如:

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

MyControl root; //using my tree
公共类MyControl:UserControl//my control和同时树
{
列出儿童;
}
对照根//使用我的树

或者还有其他方法吗?

如果我正确理解您的问题,这可能是一种方法:

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

另一种方法是使用TreeNode类的Tag属性。但是我更喜欢第一种方法。

每个树节点都有自己的事件,由树控件处理。例如,当鼠标移动到任何节点上时,MouseHover事件将在该树节点中执行,而不是直接在树控件中执行。所以,您必须在treenode中创建一个事件,然后才能从这里处理树控件事件。比如说

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

此代码将以您的形式编写。事件将添加到您的表单中。但您必须在MyControl用户控件中声明了事件

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

}

但在“TreeNode”中已经存在“MyControl”字段,它是“data”。为什么我们需要“Control”属性?好的,在我上面的例子中,我考虑的是标准的WinForms[TreeNode类]()。因此,您可以创建一个从TreeNode派生的类,并将这些实例添加到TreeView。因此,我可以使用WindowsForms.TreeNode类代替TreeNode元类。在派生类或WindowsForms.TreeNode的Tag属性中定义MyControl哪个更好?我想您不需要这个MyControl类。如果您有一个从树节点派生的类,比如YourNode类,那么可以将这些实例添加到标准树视图中。如果选择或单击一个节点,您将获得特殊的YourNode类,并且您将有权访问Control-property。如何删除包含已单击控件的TreeNode?