Search code examples
c#wpfmvvmmodern-ui

WPF Button Command not firing ICommand in ViewModel


I have a View with a button as follows:

<Button Grid.Column="2" Grid.Row="1" Content="Test" Margin="10,4" 
        Command="{Binding DataContext.CmdTestButtonClicked}" 
        CommandParameter="{Binding}" />

In the view's code-behind, I set the DataContext to the ViewModel:

public GlobalSettings()
{
    InitializeComponent();

    ...

    DataContext = Helpers.IoCHelper.GlobalSettingsVM;

    ...
}

My ViewModel derives from a base class which exposes the ICommand:

public class GlobalSettingsVM : CollectionViewModel<GlobalSettings> { ... }

public abstract class CollectionViewModel<TModel> : IInstallModuleViewModel, INotifyPropertyChanged,
        INotifyDataErrorInfo where TModel : Model, new()
{
    ...

    public ICommand CmdTestButtonClicked
    {
        get
        {
            return _testButtonClicked ??
                   (_testButtonClicked = new RelayCommand(TestButtonClicked));
        }
    }

    protected virtual void TestButtonClicked(object o)
    {
        // I never get here
    }
}

I don't have any other issues using this pattern throughout my application, however all my other implementations have the Button within a ListView, so there I have to use RelativeSource={RelativeSource AncestorType={x:Type ListView}}.

Why would this command never fire? Do I need to set a RelativeSource here as well?


Solution

  • This

    Command="{Binding DataContext.CmdTestButtonClicked}" 
    

    Implies that the Command will look for a property called DataContext in the object to which the button is bound. If the DataContext of the button is a GlobalSettingsVM this should work:

    Command="{Binding CmdTestButtonClicked}"