1

My View

<Button.ContextMenu>
   <ContextMenu x:Name="Conn_Context_button" Style="{StaticResource LeftContextMenuStyle}">
     <MenuItem Style="{StaticResource LeftContextMenuItemStyle}" Header="{x:Static properties:ResourceWrapper.Dashboard_Connection_Delete}" Click="MenuItem_DeleteConnection_Click" />
     <MenuItem Style="{StaticResource LeftContextMenuItemStyle}" Header="{x:Static properties:ResourceWrapper.Dashboard_Connection_Refresh}" Command="{Binding MyViewModel.RefreshCommand}" />
    </ContextMenu>

MyViewModel.cs

 public RelayCommand RefreshCommand { get; set; }
  RefreshCommand = new RelayCommand(RefreshConnection);
    private void RefreshConnection(object sender)
    {
       //My Logic
    }

Here RefreshCommand is not firing when i click the refresh menu item

surya
  • 191
  • 1
  • 8
  • Maybe Use ICommand instead? – Whencesoever Aug 10 '16 at 07:28
  • Maybe the datacontext is incorrect, check for binding errors in the output. If `MyViewModel` is the datacontext, `Command="{Binding RefreshCommand}` will solve this. – Natxo Aug 10 '16 at 07:31
  • 2
    It ist not so easy: Try this http://stackoverflow.com/questions/9994241/mvvm-binding-command-to-contextmenu-item – Wolfgang Feneberg Aug 10 '16 at 07:39
  • @Natxo I have already set MyViewModel as datacontext. and also tried `Command="{Binding RefreshCommand}` But the result is same.. it didnt throw any error. but nothing happens when i click the menu item. – surya Aug 10 '16 at 08:32

1 Answers1

0

As a good example, take a look to this situation.

Here's a simple piece of code taken from one of my current projets:

private void PrepareCommands()
{
    RefreshCommand = new RelayCommand(RefreshCommandMethod);
    AddConfigurationCommand = new RelayCommand(AddConfigurationCommandMethod, param => CanAddConfiguration);
    EditConfigurationCommand = new RelayCommand(EditConfigurationCommandMethod, param => CanEditConfiguration);
    RemoveConfigurationCommand = new RelayCommand(RemoveConfigurationCommandMethod, param => CanRemoveConfiguration);
}

where the commands are

#region Commands

public ICommand AddConfigurationCommand { get; set; }
public ICommand EditConfigurationCommand { get; set; }
public ICommand RemoveConfigurationCommand { get; set; }
public ICommand RefreshCommand { get; set; }

#endregion

Bindings are

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" DockPanel.Dock="Right">
    <Button Template="{StaticResource AddButton}" Command="{Binding AddConfigurationCommand}"  Margin="3,0" />
    <Button Template="{StaticResource EditButton}" Command="{Binding EditConfigurationCommand}" Margin="3,0" />
    <Button Template="{StaticResource DeleteButton}" Command="{Binding RemoveConfigurationCommand}" Margin="3,0" />
</StackPanel>

As Jan Walczak said above, try to use ICommand instead of RelayCommand. If you have created your own RelayCommand, don't forget to inherit from ICommand.

Community
  • 1
  • 1
Beltaine
  • 2,721
  • 1
  • 18
  • 22