0

I am developing my first app using MVVM and I am stuck with my command button.

In my view I have:

<Button x:Name="btSave" Command="{Binding AddContactCommand}" Content="Save" HorizontalAlignment="Left" Margin="183,186,0,0" VerticalAlignment="Top" Width="75"/>

In the code behind i have:

public partial class ContactView : Window
{
    private ContactViewModel contactVM;

    public ContactView()
    {
        InitializeComponent();

        contactVM = new ContactViewModel();
        this.DataContext = contactVM;
    }
}

In the view model I have:

public ICommand AddContactCommand { get; private set; }

void AddContact()
{
    ContactData ContactData = new ContactData();
    bSaved = ContactData.SaveContact("Theresa","Theresa","Theresa","Theresa");      
}

the AddContact() in the view model never gets fired.

What I am doing wrong?

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
  • 3
    What `AddContact()` method has to do with `AddContactCommand` ? Where do you instantiate property (`AddContactCommand = new Something()`)? See [this answer](http://stackoverflow.com/a/1468830/1997232) for an example of `ICommand`. – Sinatr Feb 01 '17 at 12:40
  • 1
    Just because you *name* the method `AddContact` and the Command `AddContactCommand` doesn't mean they are in any way related, as far as your program is concerned at least. You are missing something like this in your code: `AddContactCommand = new ClassThatImplementsICommand(AddContact)` If you don't have an ICommand implementation, google for `RelayCommand`, it's a simple implementation, that covers the basics. – Manfred Radlwimmer Feb 01 '17 at 12:46
  • Thank you for pointing me in the right direction. I have resolved it now using the RelayCommand as suugested. – Theresa Ferguson Feb 01 '17 at 13:12

1 Answers1

0

Check your DataContext as I assume that is the issue.

If your ViewModel is in the code behind in the Constructor put the following:

DataContext = this;

Otherwise if it's another class you need to do the same thing but do:

DataContext = new MyViewModel();

At least I assume this is your issue from what you have posted.

Kelly
  • 6,992
  • 12
  • 59
  • 76