c# - Unable to assign a click event to an eventhandler that uses an extended eventargs argument -
i trying assign event handler uses event argument extends system.eventargs toolstripmenuitem. when enter name of handler wants create event handler uses system.eventargs. list of recent files.
here code
recenteventargs e = new recenteventargs(); e.filename = item; toolstripmenuitem recentitem = new toolstripmenuitem(item); recentitem.click += new eventhandler(recentitem_click); mnufileopenrecentlist.dropdownitems.add(item); private void recentitem_click(object sender, recenteventargs e) { messagemanager.displaymessagebox("file -> open recent ->"); openrecentfile(e.filename); } public class recenteventargs : eventargs { private string filename; public recenteventargs() :base() { } public string filename { { return filename; } set { filename = value; } } } any appreciated.
you heading in right direction missed key parts. keep in mind in c# typed means method signatures can't change of arguments @ runtime. true delegates (that you're using if subscribing events).
as have custom eventargs, still missing delegate describes method signature new event (because you're after) calling.
// public delegate custom eventargs public delegate void recenteventhandler(object sender, recenteventargs e); now want acts toolstripmenuitem fires recent event gets clicked , send custom eventargs payload. let's create subclass handle logic:
public class recentfilemenuitem:toolstripmenuitem { private string filename; // holds path+file // constructur public recentfilemenuitem(string filename) :base(path.getfilename(filename)) { // keep our filename this.filename = filename; } // event delegate, subscribe public recenteventhandler recent; // click invokes subscribers // recent event protected override void onclick(eventargs e) { recenteventhandler recent = recent; if (recent !=null) { // create recenteventargs here recent(this, new recenteventargs { filename = filename }); } } } in above class override default onclick handler invoke subscribers recent event create new recenteventargs. notice recent delegate of type recenteventhandler.
with bits working need bring our class play.
private void form3_load(object sender, eventargs e) { recentfilemenuitem recentitem = new recentfilemenuitem("foo"); mnufileopenrecentlist.dropdownitems.add(recentitem); recentitem.recent += new recenteventhandler(show); } // method signature matches our recenteventhandler delegate public void show(object s, recenteventargs e) { messagebox.show(e.filename); } here see add new instance of recentfilemenuitem filename in constructor recent list. show method matches signature , can subscribe recent event delegate pointing method.
Comments
Post a Comment