tags:

views:

347

answers:

1

I've totally lost in the command binding that is used in MVVM. How should I bind my object to the window and/or its command to the control to get method called on the button click?

Here is a CustomerViewModel class:

    public class CustomerViewModel : ViewModelBase
{
    RelayCommand _saveCommand;
    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(param => this.Save(), param => this.CanSave);
                NotifyPropertyChanged("SaveCommand");
            }
            return _saveCommand;
        }
    }

    public void Save()
    {
        ...
    }

    public bool CanSave { get { return true; } }

    ...

ViewModelBase implements INotifyPropertyChanged interface Here is how button is bound to the command:

<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />

Instance of the CustomerViewModel is assigned to the DataContext of the window that contains a button.

The given example is not working: I've put break point into the "Save" method but execution doesn't pass to the method. I've saw a lot of examples (on the stackoverflow too), but can't figure out how binding should be specified.

Please advise, any help will be appreciated.

Thanks.

P.S. Probably I need to specify 'RelativeSource' in the Button binding... something like this:

 Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"

but which type should be specified for ancestor?

+5  A: 

What you are trying to do is to bind directly to the Save method. This is not how to do it.

Assuming that you have set the DataContext of your View to an instance of CustomerViewModel, this is how you bind to the SaveCommand:

<Button Content="Save" Margin="3" Command="{Binding SaveCommand}" />

You do not have to call NotifyPropertyChanged("SaveCommand");.

Jakob Christensen
Many thanks!ingenious simple :) Now I got how does it work :)P.S. I would add a score to the answer but don't have enough points yet.
Budda