first of all, the answer is not
.Invoke("name", new object[] { });
:) that being said, i have some old generic code that creates context menus and hot keys handlers using definitions from a config file and executes the actual methods using .Invoke() where the method signature is pre-defined or else the method is not executed
eg the method signatures are all same with these arguments
change_back_color( mycontext ctx, object sender, controlItemClickEventArgs e)
{
//...
}
I have to rework the code to include some additional functionality and would like to have Unity/MEF like functionality where the signature can include the required parameters only and order of arguments can be changed
eg the code can be changed to
[FunctionKey("myKey1")]
change_back_color( object sender, mycontext ctx )
{
//...
}
or
[FunctionKey("myKey1")]
change_back_color( mycontext ctx)
{
//...
}
Looking for guidance on how to go about it/where to look
UPDATE - the definitions are in db which can be retrieved like so
var commands = dbContext.GetCommands("current_view_name") ; // return method key, user roles etc.
// and i can use the following to match to "current_view_name"
[ImportMany(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IEnumerable<Lazy<MenuItem,IDictionary<string,object>> MenuItems
{
set
{
var fooMenuItems = value
.Where(x => x.Metadata["ContextTarget"] == "current_view_name")
.Select(x => x.Value);
// attach fooMenuItems to some context menu...
}
}
but these methods need some custom arguments as well ! any ideas ?
If you want to dynamically add context menus to your application via MEF, I would do something like this:
[Export(typeof(MenuItem)]
[ExportMetadata("ContextTarget", "foo")]
public FooMenuItemForBarAction
{
get
{
var menuItem = new MenuItem("BarAction");
menuItem.Click += delegate
{
// code to handle click here
}
return menuItem;
}
}
And then elsewhere you can import all the context menu items for "foo" like this:
[ImportMany(RequiredCreationPolicy=CreationPolicy.NonShared)]
public IEnumerable<Lazy<MenuItem,IDictionary<string,object>> MenuItems
{
set
{
var fooMenuItems = value
.Where(x => x.Metadata["ContextTarget"] == "foo")
.Select(x => x.Value);
// attach fooMenuItems to some context menu...
}
}
For hotkey handlers you can do something similar: change the exported/imported type into an Action
and replace the metadata by the key combo. Then when the user hits a key combo, you can scan all the imports for the one with the correct metadata and execute that action.
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.