我有以下控件,它只有一个TreeView和ToolStrip:
public partial class MyTreeView : UserControl
{
private string _nodeName;
public string NodeName { get { return _nodeName;} }
public MyTreeView()
{
InitializeComponent();
}
private void trv_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node == null || e.Node.Parent == null || e.Node.Parent.Parent == null)
return;
nodeName = e.Node.Parent.Parent.Text + @"\" + e.Node.Parent.Text + @"\" + e.Node.Text;
}
}
然后在我的主窗体中,其中包含MyTreeView
的实例,我尝试在那里添加Click事件:
private void mtv_Click(object sender, EventArgs e)
{
MessageBox.Show(mtv.NodeName.ToString());
}
AfterSelect
事件触发,nodeName
包含预期值,但Click
不会触发。
最终,当TreeView选项发生变化时,我将加载一个文件并在文本框中显示其内容,但我无法弄清楚如何“通知”自定义控件上发生选择更改的表单。 / p>
答案 0 :(得分:2)
试试这个
public partial class MyTreeView : UserControl
{
public delegate void ValueSelectedHandler(object sender, EventArgs e, string value);
public event ValueSelectedHandler OnValueSelected;
private string _nodeName;
public string NodeName { get { return _nodeName;} }
public MyTreeView()
{
InitializeComponent();
}
private void trv_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node == null || e.Node.Parent == null || e.Node.Parent.Parent == null)
return;
nodeName = e.Node.Parent.Parent.Text + @"\" + e.Node.Parent.Text + @"\" + e.Node.Text;
if(OnValueSelected!=null)
{
OnValueSelected(sender, e, nodeName);
}
}
}
现在以您的形式
public Form1()
{
InitializeComponent();
myTreeView1.OnValueSelected += ValueSelected;
}
private void ValueSelected(object sender, EventArgs e, string value)
{
MessageBox.Show(value);
}
答案 1 :(得分:1)
public partial class MyTreeView : UserControl
{
//create a custom event
[Browsable(true)]
public event TreeViewEventHandler AfterSelect;
public MyTreeView()
{
InitializeComponent();
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (AfterSelect != null) {
//raise the event , as it is subscribed may be in winform
AfterSelect.Invoke(sender, e);
}
}
}
现在在MytreeView控件的Select Event之后的win form subscirbe中。
public Form2()
{
InitializeComponent();
//subscribe myTreeView1.AfterSelect event
myTreeView1.AfterSelect += new TreeViewEventHandler(myTreeView1_AfterSelect);
}
private void myTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
//cast sender into TreeView
TreeView tree = sender as TreeView;
if (tree != null) {
//do your logic here
}
}