raising events with derived classes...

T

Tim Mackey

hi,
i have a class 'WebManTreeNode' that inherits from Windows forms TreeNode. i
have added a 'TextChanged' event to it, because i need to listen out for it,
but i am unable to intercept the TreeNode.Text property to raise my event
whenever the property changes.
i have tried overriding the Text property but compiler complains.

an outline of the WebManTreeNode class is below. if anyone has ideas that
would be great.
thanks
tim mackey.


public class WebManTreeNode : System.Windows.Forms.TreeNode
{
public event EventHandler TextChanged;

public WebManTreeNode(........)
{
...
this.TextChanged += new EventHandler(this.OnTextChanged);
}

public void OnTextChanged(object sender, EventArgs e)
{
// run my code...
}
 
J

Justin Rogers

You'll have better luck wrapping your own new property that delegates it's value
down to TreeNode. TreeNode
doesn't have members marked to be overriden, so you have to use them as-is.
Unless of course you use the new
keyword, which hides the base class implementation.

Here is some code that uses the new keyword, however, this doesn't work when
code operates on cast down
versions of the new node type. In the code below if you take out base.Text =
value, then you'll find that tn.Text
doesn't have a value when cast as a TreeNode. It will still have a value when
cast as an OverrideTreeNode though.

using System;
using System.Windows.Forms;

public class OverrideTreeNode : TreeNode {
private string text;

public new string Text {
get {
return this.text;
}
set {
base.Text = value;
this.text = value;
}
}

private static void Main() {
OverrideTreeNode treeNode = new OverrideTreeNode();
treeNode.Text = "Hey You";
PrintNode(treeNode);
}

private static void PrintNode(TreeNode tn) {
Console.WriteLine(tn.Text);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top