I have this context menu resource:
Unfortunately you cannot bind Executed
for a ContextMenu
as it is an event. An additional problem is that the ContextMenu
does not exist in the VisualTree
the rest of your application exists. There are solutions for both of this problems.
First of all you can use the Tag
property of the parent control of the ContextMenu
to pass-through the DataContext
of your application. Then you can use an DelegateCommand
for your CommandBinding
and there you go. Here's a small sample showing View
, ViewModel
and the DelegateCommand
implementation you would have to add to you project.
DelegateCommand.cs
public class DelegateCommand : ICommand
{
private readonly Action
MainWindowView.xaml
MainWindowView.xaml.cs
public partial class MainWindowView : Window
{
public MainWindowView()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
MainWindowViewModel.cs
public class MainWindowViewModel
{
public ObservableCollection FooViewModels { get; set; }
public MainWindowViewModel()
{
FooViewModels = new ObservableCollection();
}
}
FooViewModel.cs
public class FooViewModel
{
public ICommand HelpExecuted { get; set; }
public FooViewModel()
{
HelpExecuted = new DelegateCommand(ShowHelp);
}
private void ShowHelp(object obj)
{
// Yay!
}
}