I have this context menu resource:
I'm afraid MatthiasG beat me to it. My solution is similar:
Here the Help command is handled by the tab item's view model. It would be simple to pass a reference to the TestViewModel to each of the TestItemViewModel and have ShowHelp call back into TestViewModel if required.
public class TestViewModel
{
public TestViewModel()
{
Items = new List{
new TestItemViewModel(), new TestItemViewModel() };
}
public ICommand HelpCommand { get; private set; }
public IList Items { get; private set; }
}
public class TestItemViewModel
{
public TestItemViewModel()
{
// Expression Blend ActionCommand
HelpCommand = new ActionCommand(ShowHelp);
Header = "header";
}
public ICommand HelpCommand { get; private set; }
public string Header { get; private set; }
private void ShowHelp()
{
Debug.WriteLine("Help item");
}
}
The xaml
Alternative view models so that the help command is directed to the root view model
public class TestViewModel
{
public TestViewModel()
{
var command = new ActionCommand(ShowHelp);
Items = new List
{
new TestItemViewModel(command),
new TestItemViewModel(command)
};
}
public IList Items { get; private set; }
private void ShowHelp()
{
Debug.WriteLine("Help root");
}
}
public class TestItemViewModel
{
public TestItemViewModel(ICommand helpCommand)
{
HelpCommand = helpCommand;
Header = "header";
}
public ICommand HelpCommand { get; private set; }
public string Header { get; private set; }
}
A very simple implementation of ActionCommand
public class ActionCommand : ICommand
{
private readonly Action _action;
public ActionCommand(Action action)
{
if (action == null)
{
throw new ArgumentNullException("action");
}
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_action();
}
// not used
public event EventHandler CanExecuteChanged;
}