Reputation: 3046
I have tried few solutions given in SO, but still i'm unable to trigger the command.
XAML:
<Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType= Window}}">
<Image.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit Image" Command="{Binding PlacementTarget.Tag.EditImageCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></MenuItem>
</ContextMenu>
</Image.ContextMenu>
ViewModel:
private ICommand _EditImageCommand;
public ICommand EditImageCommand
{
get
{
return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
}
}
public void EditImage()
{
}
Upvotes: 0
Views: 5517
Reputation: 1131
Another nice workaround is to declare a static instance of your view model in App.xaml: <ViewModelTypeName x:Key="ViewModelName" d:IsDataSource="True" />
and bind like this Command="{Binding Source={StaticResource ViewModelName}, Path=MyCommand}"
I had the same issue when i needed to bind from Window and menuitem's native DataContext simultaneously. Also this solution looks not that complicated.
Upvotes: 1
Reputation: 3046
Have changed my XAML to,
<Window.Resources>
<local:ImageList x:Key="SliderViewModel"></local:ImageList>
</Window.Resources>
<Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit Image" Command="{Binding EditImageCommand, Source={StaticResource SliderViewModel}}"></MenuItem>
</ContextMenu>
</Image.ContextMenu>
</Image>
Working fine. Thanks
Upvotes: 1
Reputation: 7425
Change:
private ICommand _EditImageCommand;
private ICommand EditImageCommand
{
get
{
return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
}
}
public void EditImage()
{
}
to
private ICommand _EditImageCommand;
public ICommand EditImageCommand // has to be public
{
get
{
return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
}
}
public void EditImage()
{
}
Commands have to be public to be accessed (or internal for the sake of correctness).
Also, change your xaml to:
<Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType= Window}}">
<Image.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit Image" Command="{Binding EditImageCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></MenuItem>
</ContextMenu>
</Image.ContextMenu>
Upvotes: 2