I'm building an MVVM application in WPF and I am binding a Menu to a MenuItem model. My MenuItem class has these properties :
public class MenuItem
{
private List<MenuItem> _Items;
public MenuItem(string header, ICommand command)
{
Header = header;
Command = command;
}
public MenuItem()
{
}
public string Header { get; set; }
public List<MenuItem> Items
{
get { return _Items ?? (_Items = new List<MenuItem>()); }
set { _Items = value; }
}
public ICommand Command { get; set; }
public string CommandName { get; set; }
public object Icon { get; set; }
public bool IsCheckable { get; set; }
public bool IsChecked { get; set; }
public bool Visible { get; set; }
public bool IsSeparator { get; set; }
public string ToolTip { get; set; }
public int MenuHierarchyID { get; set; }
public int ParentMenuHierarchyID { get; set; }
public string IconPath { get; set; }
}
This MenuItem model class is populated from Data coming from a database. In this case, the only property populated from DB is CommandName.
Let's say it populates it with the string "OpenFile"
EDIT Here my MenuViewModelConstructor:
public MenuViewModel(MainViewModel _MainViewModel)
{
....
}
It has a dependency to MainViewModel because that's where the OpenFile and CanOpenFile methods live.
My MenuViewModel has a method to register Commands as follows:
private void RegisterMenuCommand(MenuItem item)
{
if(!string.IsNullOrEmpty(item.CommandName))
{
//How can I create a new RelayCommand instance from
//my CommandName string????
//e.g. item.Command = new RelayCommand(_MainViewModel.<item.CommandNameHere>, _MainViewModel."Can" + <item.CommandNameHere>
item.Command = new RelayCommand(_MainViewModel.OpenFile, _MainViewModel.CanOpenFile);
}
foreach(MenuItem child in item.Items)
{
RegisterMenuCommand(child);
}
}
By the way, the signature of RelayCommand is:
public RelayCommand(Action execute, Func<bool> canExecute)
Is it possible to instantiate my RelayCommand with Reflection or dynamic lambdas or something like that so I can use my Command string coming from the database at runtime dynamically? What would be the most optimal way?
EDIT: SOLUTION Thanks to @Nathan for pointing me to the right solution, here is my working method:
private void RegisterMenuCommand(MenuItem item)
{
if(!string.IsNullOrEmpty(item.CommandName))
{
MethodInfo method1 = _MainViewModel.GetType().GetMethod(item.CommandName);
Delegate d1 = Delegate.CreateDelegate(typeof(Action),_MainViewModel, method1);
MethodInfo method2 = _MainViewModel.GetType().GetMethod("Can" + item.CommandName);
Delegate d2 = Delegate.CreateDelegate(typeof (Func<bool>),_MainViewModel, method2);
item.Command = new RelayCommand((Action)d1, (Func<bool>)d2);
}
foreach(MenuItem child in item.Items)
{
RegisterMenuCommand(child);
}
}
I am using .NET 4.0
Thanks!