0

Sorry if this is a stupid question but I cannot seem to work it out, basically I have a button on a window that is to save data. I have added a class of RelayCommand as mentioned here (Top Answer) Binding Button click to a method Everytime I run my project the ICommand SaveCommand Method is hit. From here it created a loop and continously loops. However when the window appears pushing the Save button does not actually cause the ICommand SaveCommand Method to be hit. How can I resolve this? Thanks everyone.

My View:

<av:Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="81" Height="44" Margin="52,0,0,20" av:Grid.RowSpan="2" Command ="{Binding SaveCommand}"/>

My ViewModel:

private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private ICommand _saveCommand;

    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => this.SaveObject(),
                    param => this.CanSave()
                    );
            }
            return _saveCommand;
        }
    }

    private bool CanSave()
    {
        // Verify command can be executed here

        return true;
    }

    private void SaveObject()
    {
        // Save command execution logic
    }

RelayCommand Class:

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameters)
    {
        return _canExecute == null ? true : _canExecute(parameters);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameters)
    {
        _execute(parameters);
    }

    #endregion // ICommand Members
}
Community
  • 1
  • 1
David B
  • 889
  • 2
  • 11
  • 29
  • is the datacontext of the view set up to be equal to the view model? – JKennedy Apr 02 '15 at 15:09
  • Yes the DataContext is set to be this ViewModel @user1 – David B Apr 02 '15 at 15:18
  • Any code in your window/Viewmodel's constructor? – Bolu Apr 02 '15 at 15:25
  • also should be `if(PropertyChanged != null)` – Xi Sigma Apr 02 '15 at 15:28
  • Ive commented out everything in my Constructor. This ViewModel implements INotifyPropertyChanged. All it contains now is IList properties that are Public and the code above, issue still occurs. – David B Apr 02 '15 at 15:31
  • and what is the av:Button? – Xi Sigma Apr 02 '15 at 15:37
  • It has the type of button, a standard WPF button. @decoherence – David B Apr 02 '15 at 15:44
  • whatever the problem is, its not in the code you are showing – Xi Sigma Apr 02 '15 at 15:49
  • ok I have commented everything out but this part, the button now fires fine. However if you put a breakpoint in CanSave() this is hit and repeatably executed, is this normal behaviour? – David B Apr 02 '15 at 15:50
  • @decoherence If I put a breakpoint on ICommand SaveCommand, run the project it gets hit everytime. However only executes the CanSave(), if the button is clicked it executes the SaveObject() - As I would expect. – David B Apr 02 '15 at 15:59
  • 1
    repeatable execute `CanSave()` is fine, as it needs to be evaluated to disable/enable the button. – Bolu Apr 02 '15 at 16:06

2 Answers2

3

You made a mistake/typo in SaveCommand's get section, you should change

if (_saveCommand != null) to if (_saveCommand == null)

Bolu
  • 8,696
  • 4
  • 38
  • 70
  • Thanks I have changed that yet still seeing the same behaviour ie, it fires when the window is loaded and not when the button is clicked, and loops also. – David B Apr 02 '15 at 15:15
  • @DavidBeaumont, you probably need to show us more code, as you currently posted code can't produce your error. Make sure you didn't mis-place `CanSave()` and `SaveObject()` in your command. – Bolu Apr 02 '15 at 15:19
0

Your CanSave method return false.

Consider resolving that.

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118